Skip to content

Instantly share code, notes, and snippets.

@mbostock mbostock/.block
Last active Jul 21, 2019

Embed
What would you like to do?
Canvas Donut
license: gpl-3.0
redirect: https://observablehq.com/@d3/donut-chart
age population
<5 2704659
5-13 4499890
14-17 2159981
18-24 3853788
25-44 14106543
45-64 8819342
≥65 612463
<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="//d3js.org/d3.v4.0.0-alpha.4.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
var width = canvas.width,
height = canvas.height,
radius = Math.min(width, height) / 2;
var colors = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"];
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70)
.context(context);
var labelArc = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40)
.context(context);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.population; });
context.translate(width / 2, height / 2);
d3.requestTsv("data.tsv", function(d) {
d.population = +d.population;
return d;
}, function(error, data) {
if (error) throw error;
var arcs = pie(data);
arcs.forEach(function(d, i) {
context.beginPath();
arc(d);
context.fillStyle = colors[i];
context.fill();
});
context.beginPath();
arcs.forEach(arc);
context.strokeStyle = "#fff";
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#000";
arcs.forEach(function(d) {
var c = labelArc.centroid(d);
context.fillText(d.data.age, c[0], c[1]);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.