d3 Pie Example
by azcoov
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
body {
font: 10px sans-serif;
}
.arc path {
stroke: #999999;
stroke-width: 2;
}
.arc:last-child path {
stroke: red;
stroke-width: 3;
}
.slice text {
font-size: 16pt;
font-family: Arial;
}
JavaScript
dataSet = [
{ "event": "opened:media-editor", "count": 76710.0 },
{ "event": "media-upload", "count": 61812.0 },
{ "event": "gallery-reorder", "count": 44015.0 },
{ "event": "loaded-manager", "count": 24424.0 },
{ "event": "opened:upload-image", "count": 19878.0 }
]
var canvasWidth = 400, //width
canvasHeight = 400, //height
outerRadius = 100, //radius
color = d3.scale.category20(); //builtin range of colors
var vis = d3.select("body")
.append("svg:svg") //create the SVG element inside the <body>
.data([dataSet]) //associate our data with the document
.attr("width", canvasWidth) //set the width of the canvas
.attr("height", canvasHeight) //set the height of the canvas
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + 1.5*outerRadius + "," + 1.5*outerRadius + ")") // relocate center of pie to 'outerRadius,outerRadius'
// This will create <path> elements for us using arc data...
var arc = d3.svg.arc()
.innerRadius(outerRadius * .5)
.outerRadius(outerRadius);
var outerArc = d3.svg.arc()
.outerRadius(outerRadius+10);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.count; }) // Binding each value to the pie
.sort( function(d) { return null; } );
// Select all <g> elements with class slice (there aren't any yet)
var arcs = vis.selectAll("g.slice")
// Associate the generated pie data (an array of arcs, each having startAngle,
// endAngle and value properties)
.data(pie)
// This will create <g> elements for every "extra" data element that should be associated
// with a selection. The result is creating a <g> for every object in the data array
.enter()
// Create a group to hold each slice (we will have a <path> and a <text>
// element associated with each slice)
...