Part of the video course: D3.js in Motion.
This pie chart shows the estimated number of adherents to various religions in 2010. The data is from the Pew Research Center Global Religious Landscape data set.
xxxxxxxxxx
<meta charset="utf-8">
<style>
body {
font-family: helvetica;
}
.label {
font-size: 10px;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<svg width="660" height="500"></svg>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [
{
"label": "Currency",
"value": "318.70",
"isDecreasing": false,
"change": 13.7
},
{
"label": "Equity",
"value": "36115.70",
"isDecreasing": false,
"change": 49.35
},
{
"label": "Volatility",
"value": "1099.70",
"isDecreasing": false,
"change": 5.4
},
{
"label": "Commodity",
"value": "1122.30",
"isDecreasing": true,
"change": 5.35
},
{
"label": "Alternatives",
"value": "113.00",
"isDecreasing": true,
"change": 7.27
},
{
"label": "Real Estate",
"value": "250.70",
"isDecreasing": false,
"change": 35.25
},
{
"label": "Bond",
"value": "4508.10",
"isDecreasing": false,
"change": 6.57
}
];
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = Math.min(width, height) / 3,
g = svg.append("g").attr("transform", "translate(" + radius + ",200 )");
var color = d3.scaleOrdinal(d3.schemeCategory10);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.value; });
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var label = d3.arc()
.outerRadius(radius + 10)
.innerRadius(radius + 10);
svg.append("text")
.attr("transform", "translate(20,50)")
.attr("font-size", "1.5em")
.text("Type");
var arc = g.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
arc.append("path")
.attr("d", path)
.attr("fill", function(d) { return color(d.data.label); });
// Setup legend
var legendDotSize = 30;
var legendWrapper = svg.append("g")
.attr("class", "legend")
.attr("transform", function(d) { return "translate("+radius*2+",80)"; })
// The text of the legend
var legendText = legendWrapper.selectAll("text")
.data(data);
legendText.enter().append("text")
.attr("y", function(d, i) { return i * legendDotSize + 12; })
.attr("x", 20)
.merge(legendText)
.text(function(d) {
return d.label +' - '+d.value+' ('+ d.change + '%)';
});
legendText.exit().remove();
// The dots of the legend
var legendDot = legendWrapper.selectAll("rect")
.data(data);
legendDot.enter().append("rect")
.attr("y", function(d, i) { return i * legendDotSize; })
.attr("rx", legendDotSize * 0.5)
.attr("ry", legendDotSize * 0.5)
.attr("width", legendDotSize * 0.5)
.attr("height", legendDotSize * 0.5)
.merge(legendDot)
.style("fill", function(d) { return color(d.label); });
legendDot.exit().remove();
</script>
https://d3js.org/d3.v4.min.js