Skip to content

Instantly share code, notes, and snippets.

@lkopacz
Last active July 11, 2019 15:45
Show Gist options
  • Save lkopacz/d1a86ffa3d1af8f180cd347cbf3c88f3 to your computer and use it in GitHub Desktop.
Save lkopacz/d1a86ffa3d1af8f180cd347cbf3c88f3 to your computer and use it in GitHub Desktop.
Pie Chart (d3js v4)
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [10, 20, 100];
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888"]);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var labelArc = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data); });
g.append("text")
.attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.data; });
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment