Raphael Pie Chart
This post is the result of a student question about pie charts. I used Raphael to draw these chart. If you haven’t tried Raphael yet I highly recommend it….
Here is the source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Pie</title> <script src="raphael-min.js"></script> <script> window.onload = function(){ var r = new Raphael("paper", 500, 400); var chartA = drawPieChart({ radius : 100, segments : [ {value : 0.3, fill : "#52718c", stroke : "white"}, {value : 0.3, fill : "#6a8ead", stroke : "white"}, {value : 0.25, fill : "#88aecf", stroke : "white"}, {value : 0.15, fill : "#b1cce3", stroke : "white"} ], resolution : 0.1 }); chartA.translate(130, 150); var chartB = drawPieChart({ radius : 100, segments : [ {value : 0.2, fill : "#6a8ead", stroke : "white"}, {value : 0.1, fill : "#88aecf", stroke : "white"}, {value : 0.1, fill : "#b1cce3", stroke : "white"}, {value : 0.05, fill : "#52718c", stroke : "white"}, {value : 0.2, fill : "#52718c", stroke : "white"}, {value : 0.3, fill : "#698b91", stroke : "white"}, {value : 0.05, fill : "#52718c", stroke : "white"} ], resolution : 0.1 }); chartB.translate(370, 150); // functions to make the chart: function drawPieChart(p){ if (!p.resolution) p.resolution = 0.1; var TWO_PI = Math.PI * 2; var pie = r.set(); var leng = p.segments.length; var offsetAngle = 0; for (var i = 0; i < leng; i++){ var segData = p.segments[i]; // angle is percent of TWO_PI var angle = TWO_PI * segData.value; var seg = drawSegment(p.radius, angle, offsetAngle, p.resolution); //seg.translate(100, 100); seg.attr({stroke:segData.stroke,fill:segData.fill}); pie.push(seg); offsetAngle += angle; } return pie; } function polarPath(radius, theta, rotation){ var x, y; x = radius * Math.cos(theta + rotation); y = radius * Math.sin(theta + rotation); return "L " + x + " " + y + " "; } // value and rotation are now in radians function drawSegment(radius, value, rotation, resolution){ if (!resolution) resolution = 0.1; var path = "M 0 0 "; for (var i = 0; i < value; i+=resolution){ path += polarPath(radius, i, rotation); } path += polarPath(radius, value, rotation); path += "L 0 0"; var seg = r.path(path); return seg; } } </script> <style> #paper{ width : 500px; height : 400px; } </style> </head> <body> <div id="paper"></div> </body> </html> |
15. June 2011 um 20:30
hi,
isn’t working for me, i’m on chrome 12.0.742.100 in mac os 10.6.7
cp
22. June 2011 um 05:52
strange, I’ll look into that
3. January 2013 um 08:36
How would you animate individual pie segments using these functions?
I’m trying to animate a single segment from 0% to 91%.
Thanks