Skip to content

Instantly share code, notes, and snippets.

@vigorousnorth
Last active May 28, 2019 12:15
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save vigorousnorth/7331bb51d4f0c2ae0314 to your computer and use it in GitHub Desktop.
Pie chart with rotated wedge labels

Pie chart with rotated pie wedge labels.

<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var piecolors = d3.scale.category20c();
var w = 600,
h = 460,
r = (Math.min(w, h) - 50) / 2;
d3.csv("makes.csv", function(error, data) {
var svgPie = d3.select("#chart").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
var arc = d3.svg.arc()
.outerRadius(r - 12)
.innerRadius(2);
var labelArc = d3.svg.arc()
.outerRadius(r + 20)
.innerRadius(r-5);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.cars; });
var pie = svgPie.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
pie.append("path")
.attr("d", arc)
.style("fill", function(d) { return piecolors(d.data.make); });
pie.append("text")
.attr("transform", function(d) {
var midAngle = d.endAngle < Math.PI ? d.startAngle/2 + d.endAngle/2 : d.startAngle/2 + d.endAngle/2 + Math.PI ;
return "translate(" + labelArc.centroid(d)[0] + "," + labelArc.centroid(d)[1] + ") rotate(-90) rotate(" + (midAngle * 180/Math.PI) + ")"; })
.attr("dy", ".35em")
.attr('text-anchor','middle')
.text(function(d) { return (d.data.cars > 10000) ? d.data.make : null; });
});
</script>
<style>
body {
font: 10px 'Open sans', sans-serif;
}
.line {
fill: none;
stroke: black;
stroke-width: 1.2px;
}
div#chart {width: 100%;}
</style>
<body>
<div id="chart"></div>
</body>
make cars
Ford 148318
Chevy 147864
Toyota 139514
Honda 71312
Subaru 70097
Dodge 60532
GMC 57995
Jeep 52065
Nissan 44745
Hyundai 32127
Volkswagen 28140
Chrysler 22181
Buick 20454
Kia 17674
Volvo 17248
Mazda 15021
Pontiac 14879
Mercedes 9983
Saturn 9391
Others 77035
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment