Flot Pie Charts
June 28, 2011
I have many pie chart that have the same three segments, one features contest wins, another top six places, and a third unplaced. I wanted to have each segment colour coded in a specific way. Unfortunately the Raphael pie chart code I was using did not support this, and always defaulted to assigning colours in the order of the size of the slice of pie.
I switched to using the Flot pie chart to sort this out.
Imports
The JavaScript libraries required to be included are:
<script src="/site_media/flot/jquery.flot.min.js" type="text/javascript"></script> <script src="/site_media/flot/jquery.flot.pie.min.js" type="text/javascript"></script>
JavaScript
Here's the code used to produce the pie chart:
var lPieData = [ { label: "Wins", data: {{Wins}}, color: "#ffc600" }, { label: "Top Six", data: {{TopSixNotWin}}, color: "#99ccff" }, { label: "Unplaced", data: {{Unplaced}}, color: "#316497" } ]; $.plot($("#flot_pie"), lPieData, { series: { pie: { show: true, label: { formatter: function(label, series){ return '<div style="font-size:8pt;text-align:center;padding:2px;color:black;">' +label+'<br/>'+series.data[0][1]+" (" +Math.round(series.percent)+'%)</div>'; } } } }, legend: { show: false } });
Note that:
- Colours for the pie slices are defined alongside the data and labels.
- We use a function to make sure all the labels for the pie segments are in black. They will default to the colour of the pie slice.
- This also changes what is displayed - we change the
slice title
,slice value
andslice percentage
.
HTML
This solution also requires a HTML tag to insert into - this is identified with the id flot_pie
:
<div id="flot_pie"></div>
CSS
This tag needs some styling to set the width and height of the pie chart:
#flot_pie { width: 220px; height: 220px; }