2 Flot plugin for rendering pie charts. The plugin assumes the data is
3 coming is as a single data value for each series, and each of those
4 values is a positive value or zero (negative numbers don't make
5 any sense and will cause strange effects). The data values do
6 NOT need to be passed in as percentage values because it
7 internally calculates the total and percentages.
9 * Created by Brian Medendorp, June 2009
10 * Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars
13 2009-10-22: lineJoin set to round
14 2009-10-23: IE full circle fix, donut
15 2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera
16 2009-11-17: Added IE hover capability submitted by Anthony Aragues
17 2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well)
20 Available options are:
24 radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
25 innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
26 startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
27 tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
29 top: integer value to move the pie up or down
30 left: integer value to move the pie left or right, or 'auto'
33 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
34 width: integer pixel width of the stroke
37 show: true/false, or 'auto'
38 formatter: a user-defined function that modifies the text/style of the label text
39 radius: 0-1 for percentage of fullsize, or a specified pixel length
41 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
44 threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
47 threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
48 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
49 label: any text value of what the combined slice should be labeled
57 More detail and specific examples can be found in the included HTML file.
63 function init(plot) // this is the "body" of the plugin
68 var centerLeft = null;
72 var redrawAttempts = 10;
75 var processed = false;
78 // interactive variables
81 // add hook to determine if pie plugin in enabled, and then perform necessary operations
82 plot.hooks.processOptions.push(checkPieEnabled);
83 plot.hooks.bindEvents.push(bindEvents);
85 // check to see if the pie plugin is enabled
86 function checkPieEnabled(plot, options)
88 if (options.series.pie.show)
91 options.grid.show = false;
94 if (options.series.pie.label.show=='auto')
95 if (options.legend.show)
96 options.series.pie.label.show = false;
98 options.series.pie.label.show = true;
101 if (options.series.pie.radius=='auto')
102 if (options.series.pie.label.show)
103 options.series.pie.radius = 3/4;
105 options.series.pie.radius = 1;
108 if (options.series.pie.tilt>1)
109 options.series.pie.tilt=1;
110 if (options.series.pie.tilt<0)
111 options.series.pie.tilt=0;
113 // add processData hook to do transformations on the data
114 plot.hooks.processDatapoints.push(processDatapoints);
115 plot.hooks.drawOverlay.push(drawOverlay);
118 plot.hooks.draw.push(draw);
122 // bind hoverable events
123 function bindEvents(plot, eventHolder)
125 var options = plot.getOptions();
127 if (options.series.pie.show && options.grid.hoverable)
128 eventHolder.unbind('mousemove').mousemove(onMouseMove);
130 if (options.series.pie.show && options.grid.clickable)
131 eventHolder.unbind('click').click(onClick);
135 // debugging function that prints out an object
136 function alertObject(obj)
139 function traverse(obj, depth)
143 for (var i = 0; i < obj.length; ++i)
145 for (var j=0; j<depth; j++)
148 if( typeof obj[i] == "object")
151 traverse(obj[i], depth+1);
155 msg += ''+i+': '+obj[i]+'\n';
163 function calcTotal(data)
165 for (var i = 0; i < data.length; ++i)
167 var item = parseFloat(data[i].data[0][1]);
173 function processDatapoints(plot, series, data, datapoints)
179 canvas = plot.getCanvas();
180 target = $(canvas).parent();
181 options = plot.getOptions();
183 plot.setData(combine(plot.getData()));
189 legendWidth = target.children().filter('.legend').children().width();
191 // calculate maximum radius and center point
192 maxRadius = Math.min(canvas.width,(canvas.height/options.series.pie.tilt))/2;
193 centerTop = (canvas.height/2)+options.series.pie.offset.top;
194 centerLeft = (canvas.width/2);
196 if (options.series.pie.offset.left=='auto')
197 if (options.legend.position.match('w'))
198 centerLeft += legendWidth/2;
200 centerLeft -= legendWidth/2;
202 centerLeft += options.series.pie.offset.left;
204 if (centerLeft<maxRadius)
205 centerLeft = maxRadius;
206 else if (centerLeft>canvas.width-maxRadius)
207 centerLeft = canvas.width-maxRadius;
210 function fixData(data)
212 for (var i = 0; i < data.length; ++i)
214 if (typeof(data[i].data)=='number')
215 data[i].data = [[1,data[i].data]];
216 else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined')
218 if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined')
219 data[i].label = data[i].data.label; // fix weirdness coming from flot
220 data[i].data = [[1,0]];
227 function combine(data)
229 data = fixData(data);
233 var color = options.series.pie.combine.color;
236 for (var i = 0; i < data.length; ++i)
238 // make sure its a number
239 data[i].data[0][1] = parseFloat(data[i].data[0][1]);
240 if (!data[i].data[0][1])
241 data[i].data[0][1] = 0;
243 if (data[i].data[0][1]/total<=options.series.pie.combine.threshold)
245 combined += data[i].data[0][1];
248 color = data[i].color;
253 data: [[1,data[i].data[0][1]]],
254 color: data[i].color,
255 label: data[i].label,
256 angle: (data[i].data[0][1]*(Math.PI*2))/total,
257 percent: (data[i].data[0][1]/total*100)
263 data: [[1,combined]],
265 label: options.series.pie.combine.label,
266 angle: (combined*(Math.PI*2))/total,
267 percent: (combined/total*100)
272 function draw(plot, newCtx)
274 if (!target) return; // if no series were passed
278 var slices = plot.getData();
281 while (redraw && attempts<redrawAttempts)
288 if (options.series.pie.tilt<=0.8)
292 if (attempts >= redrawAttempts) {
294 target.prepend('<div class="error">Could not draw pie with labels contained inside canvas</div>');
297 if ( plot.setSeries && plot.insertLegend )
299 plot.setSeries(slices);
303 // we're actually done at this point, just defining internal functions at this point
307 ctx.clearRect(0,0,canvas.width,canvas.height);
308 target.children().filter('.pieLabel, .pieLabelBackground').remove();
311 function drawShadow()
319 if (options.series.pie.radius>1)
320 var radius = options.series.pie.radius;
322 var radius = maxRadius * options.series.pie.radius;
324 if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge)
325 return; // shadow would be outside canvas, so don't draw it
328 ctx.translate(shadowLeft,shadowTop);
329 ctx.globalAlpha = alpha;
330 ctx.fillStyle = '#000';
332 // center and rotate to starting position
333 ctx.translate(centerLeft,centerTop);
334 ctx.scale(1, options.series.pie.tilt);
337 for (var i=1; i<=edge; i++)
340 ctx.arc(0,0,radius,0,Math.PI*2,false);
350 startAngle = Math.PI*options.series.pie.startAngle;
353 if (options.series.pie.radius>1)
354 var radius = options.series.pie.radius;
356 var radius = maxRadius * options.series.pie.radius;
358 // center and rotate to starting position
360 ctx.translate(centerLeft,centerTop);
361 ctx.scale(1, options.series.pie.tilt);
362 //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
366 var currentAngle = startAngle;
367 for (var i = 0; i < slices.length; ++i)
369 slices[i].startAngle = currentAngle;
370 drawSlice(slices[i].angle, slices[i].color, true);
374 // draw slice outlines
376 ctx.lineWidth = options.series.pie.stroke.width;
377 currentAngle = startAngle;
378 for (var i = 0; i < slices.length; ++i)
379 drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
386 if (options.series.pie.label.show)
389 // restore to original state
392 function drawSlice(angle, color, fill)
398 ctx.fillStyle = color;
401 ctx.strokeStyle = color;
402 ctx.lineJoin = 'round';
406 if (Math.abs(angle - Math.PI*2) > 0.000000001)
407 ctx.moveTo(0,0); // Center of the pie
408 else if ($.browser.msie)
410 //ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera
411 ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false);
413 //ctx.rotate(angle); // This doesn't work properly in Opera
414 currentAngle += angle;
422 function drawLabels()
424 var currentAngle = startAngle;
427 if (options.series.pie.label.radius>1)
428 var radius = options.series.pie.label.radius;
430 var radius = maxRadius * options.series.pie.label.radius;
432 for (var i = 0; i < slices.length; ++i)
434 if (slices[i].percent >= options.series.pie.label.threshold*100)
435 drawLabel(slices[i], currentAngle, i);
436 currentAngle += slices[i].angle;
439 function drawLabel(slice, startAngle, index)
441 if (slice.data[0][1]==0)
445 var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
447 text = lf(slice.label, slice);
451 text = plf(text, slice);
453 var halfAngle = ((startAngle+slice.angle) + startAngle)/2;
454 var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
455 var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
457 var html = '<span class="pieLabel" id="pieLabel'+index+'" style="position:absolute;top:' + y + 'px;left:' + x + 'px;">' + text + "</span>";
459 var label = target.children('#pieLabel'+index);
460 var labelTop = (y - label.height()/2);
461 var labelLeft = (x - label.width()/2);
462 label.css('top', labelTop);
463 label.css('left', labelLeft);
465 // check to make sure that the label is not outside the canvas
466 if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0)
469 if (options.series.pie.label.background.opacity != 0) {
470 // put in the transparent background separately to avoid blended labels and label boxes
471 var c = options.series.pie.label.background.color;
475 var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;';
476 $('<div class="pieLabelBackground" style="position:absolute;width:' + label.width() + 'px;height:' + label.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').insertBefore(label).css('opacity', options.series.pie.label.background.opacity);
478 } // end individual label function
479 } // end drawLabels function
480 } // end drawPie function
481 } // end draw function
483 // Placed here because it needs to be accessed from multiple locations
484 function drawDonutHole(layer)
487 if(options.series.pie.innerRadius > 0)
489 // subtract the center
491 innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
492 layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color
494 layer.fillStyle = options.series.pie.stroke.color;
495 layer.arc(0,0,innerRadius,0,Math.PI*2,false);
503 layer.strokeStyle = options.series.pie.stroke.color;
504 layer.arc(0,0,innerRadius,0,Math.PI*2,false);
508 // TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
512 //-- Additional Interactive related functions --
514 function isPointInPoly(poly, pt)
516 for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
517 ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
518 && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
523 function findNearbySlice(mouseX, mouseY)
525 var slices = plot.getData(),
526 options = plot.getOptions(),
527 radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
529 for (var i = 0; i < slices.length; ++i)
537 ctx.moveTo(0,0); // Center of the pie
538 //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
539 ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false);
541 x = mouseX-centerLeft;
542 y = mouseY-centerTop;
543 if(ctx.isPointInPath)
545 if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop))
547 //alert('found slice!');
549 return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
554 // excanvas for IE doesn;t support isPointInPath, this is a workaround.
555 p1X = (radius * Math.cos(s.startAngle));
556 p1Y = (radius * Math.sin(s.startAngle));
557 p2X = (radius * Math.cos(s.startAngle+(s.angle/4)));
558 p2Y = (radius * Math.sin(s.startAngle+(s.angle/4)));
559 p3X = (radius * Math.cos(s.startAngle+(s.angle/2)));
560 p3Y = (radius * Math.sin(s.startAngle+(s.angle/2)));
561 p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5)));
562 p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5)));
563 p5X = (radius * Math.cos(s.startAngle+s.angle));
564 p5Y = (radius * Math.sin(s.startAngle+s.angle));
565 arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]];
567 // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
568 if(isPointInPoly(arrPoly, arrPoint))
571 return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
581 function onMouseMove(e)
583 triggerClickHoverEvent('plothover', e);
588 triggerClickHoverEvent('plotclick', e);
591 // trigger click or hover event (they send the same parameters so we share their code)
592 function triggerClickHoverEvent(eventname, e)
594 var offset = plot.offset(),
595 canvasX = parseInt(e.pageX - offset.left),
596 canvasY = parseInt(e.pageY - offset.top),
597 item = findNearbySlice(canvasX, canvasY);
599 if (options.grid.autoHighlight)
601 // clear auto-highlights
602 for (var i = 0; i < highlights.length; ++i)
604 var h = highlights[i];
605 if (h.auto == eventname && !(item && h.series == item.series))
606 unhighlight(h.series);
610 // highlight the slice
612 highlight(item.series, eventname);
614 // trigger any hover bind events
615 var pos = { pageX: e.pageX, pageY: e.pageY };
616 target.trigger(eventname, [ pos, item ]);
619 function highlight(s, auto)
621 if (typeof s == "number")
624 var i = indexOfHighlight(s);
627 highlights.push({ series: s, auto: auto });
628 plot.triggerRedrawOverlay();
631 highlights[i].auto = false;
634 function unhighlight(s)
639 plot.triggerRedrawOverlay();
642 if (typeof s == "number")
645 var i = indexOfHighlight(s);
648 highlights.splice(i, 1);
649 plot.triggerRedrawOverlay();
653 function indexOfHighlight(s)
655 for (var i = 0; i < highlights.length; ++i)
657 var h = highlights[i];
664 function drawOverlay(plot, octx)
666 //alert(options.series.pie.radius);
667 var options = plot.getOptions();
668 //alert(options.series.pie.radius);
670 var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
673 octx.translate(centerLeft, centerTop);
674 octx.scale(1, options.series.pie.tilt);
676 for (i = 0; i < highlights.length; ++i)
677 drawHighlight(highlights[i].series);
683 function drawHighlight(series)
685 if (series.angle < 0) return;
687 //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
688 octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor
691 if (Math.abs(series.angle - Math.PI*2) > 0.000000001)
692 octx.moveTo(0,0); // Center of the pie
693 octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false);
700 } // end init (plugin body)
702 // define pie specific options and their default values
707 radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
708 innerRadius:0, /* for donut */
721 formatter: function(label, slice){
722 return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+Math.round(slice.percent)+'%</div>';
723 }, // formatter function
724 radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
729 threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
732 threshold: -1, // percentage at which to combine little slices into one larger slice
733 color: null, // color to give the new slice (auto-generated if null)
734 label: 'Other' // label to give the new slice
737 //color: '#FFF', // will add this functionality once parseColor is available
744 $.plot.plugins.push({