Simple D3 Pie Chart
aAn example of a simple pie chart drawn with D3.js
HTML
<div id="chart"></div>
JavaScript
var w = 400;
var h = 400;
var r = h / 2;
var color = d3.scale.category20c();
var data = [{
"label": "Category A",
"value": 20
}, {
"label": "Category B",
"value": 50
}, {
"label": "Category C",
"value": 30
}];
var vis = d3.select('#chart').append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function(d) {
return d.value;
});
// declare an arc generator function
var arc = d3.svg.arc().outerRadius(r);
// select paths, use arc generator to draw
var g = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice").on("mouseover", function(d) {
d3.select(this).select('path').attr('fill', 'blue');
d3.select(this).select('text').attr('fill', 'white');
})
.on("mouseout", function(d, i, j) {
d3.select(this).select('path').attr('fill', function(d, j) {
return color(i);
});
d3.select(this).select('text').attr('fill', 'black');
});;
g.append("svg:path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", function(d) {
// log the result of the arc generator to show how cool it is :)
console.log(arc(d));
return arc(d);
});
// add the text
g.append("svg:text").attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
}).attr("text-anchor", "middle").text(function(d, i) {
return data[i].label;
});