D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jwilber
Full window
Github gist
d3v5 pie
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) svg.append("text") .text("Edit the code below to change me!") .attr("y", 200) .attr("x", 120) .attr("font-size", 36) .attr("font-family", "monospace") height = Math.min(width, 500) arc = d3.arc() .innerRadius(0) .outerRadius(Math.min(width, height) / 2 - 1) arcLabel = { const radius = Math.min(width, height) / 2 * 0.8; return d3.arc().innerRadius(radius).outerRadius(radius); } pie = d3.pie() .sort(null) .value(d => d.value) const data = d3.csv("https://gist.githubusercontent.com/mbostock/a3541c73fdccd432acc8b11bf9f02641/raw/2bd0fce0bf34b020e93c5f6527b5a9d08c33ff06/population-by-age.csv", d3.autoType) const color = d3.scaleOrdinal() .domain(data.map(d => d.name)) .range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length).reverse()) const arcs = pie(data); const svg = d3.create("svg") .attr("viewBox", [-width / 2, -height / 2, width, height]); svg.append("g") .attr("stroke", "white") .selectAll("path") .data(arcs) .join("path") .attr("fill", d => color(d.data.name)) .attr("d", arc) .append("title") .text(d => `${d.data.name}: ${d.data.value.toLocaleString()}`); svg.append("g") .attr("font-family", "sans-serif") .attr("font-size", 12) .attr("text-anchor", "middle") .selectAll("text") .data(arcs) .join("text") .attr("transform", d => `translate(${arcLabel.centroid(d)})`) .call(text => text.append("tspan") .attr("y", "-0.4em") .attr("font-weight", "bold") .text(d => d.data.name)) .call(text => text.filter(d => (d.endAngle - d.startAngle) > 0.25).append("tspan") .attr("x", 0) .attr("y", "0.7em") .attr("fill-opacity", 0.7) .text(d => d.data.value.toLocaleString())); </script> </body>
https://d3js.org/d3.v5.min.js