Pie sort.
From D3 in Depth book by Peter Cook.
license: gpl-3.0 | |
height: 230 | |
border: no |
Pie sort.
From D3 in Depth book by Peter Cook.
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<head> | |
<title>Pie sort</title> | |
</head> | |
<style> | |
path { | |
fill: orange; | |
stroke: white; | |
} | |
text { | |
font-family: "Helvetica Neue", Helvetica, sans-serif; | |
font-size: 12px; | |
font-weight: bold; | |
fill: white; | |
text-anchor: middle; | |
} | |
</style> | |
<body> | |
<svg width="700" height="220"> | |
<g transform="translate(300, 110)"></g> | |
</svg> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> | |
<script> | |
var pieGenerator = d3.pie() | |
.value(function(d) {return d.quantity;}) | |
.sort(function(a, b) { | |
return a.name.localeCompare(b.name); | |
}); | |
var fruits = [ | |
{name: 'Apples', quantity: 20}, | |
{name: 'Bananas', quantity: 40}, | |
{name: 'Cherries', quantity: 50}, | |
{name: 'Damsons', quantity: 10}, | |
{name: 'Elderberries', quantity: 30}, | |
]; | |
// Create an arc generator with configuration | |
var arcGenerator = d3.arc() | |
.innerRadius(20) | |
.outerRadius(100); | |
var arcData = pieGenerator(fruits); | |
// Create a path element and set its d attribute | |
d3.select('g') | |
.selectAll('path') | |
.data(arcData) | |
.enter() | |
.append('path') | |
.attr('d', arcGenerator); | |
// Labels | |
d3.select('g') | |
.selectAll('text') | |
.data(arcData) | |
.enter() | |
.append('text') | |
.each(function(d) { | |
var centroid = arcGenerator.centroid(d); | |
d3.select(this) | |
.attr('x', centroid[0]) | |
.attr('y', centroid[1]) | |
.attr('dy', '0.33em') | |
.text(d.data.name); | |
}); | |
</script> | |
</body> | |
</html> |