D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
EmbraceLife
Full window
Github gist
27.pieChart
Built with
blockbuilder.org
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>D3: Pie layout</title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script> <style type="text/css"> text { font-family: sans-serif; font-size: 12px; fill: white; } </style> </head> <body> <script type="text/javascript"> //Width and height var w = 400; var h = 400; var dataset = [ 5, 10, 20, 45, 6, 25 ]; var outerRadius = w / 2; var innerRadius = w/4; // 0 => a pie // ---- path use arc func to generate an arc var arc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius); // ---- create a pie func var pie = d3.pie(); // Test: // console.log(pie(dataset)); // ---- Easy colors accessible via a 10-step ordinal scale var color = d3.scaleOrdinal(d3.schemeCategory10); // Test: // for(var i = 0; i < 6; i++){ // console.log(color(i)); // } var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); var arcs = svg.selectAll("g.arc") .data(pie(dataset)) .enter() .append("g") .attr("class", "arc") .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")"); arcs.append("path") .attr("fill", function(d, i) { console.log(color(i)); return color(i); }) // A paths path description is defined in the d attribute. So here we call the arc generator, which generates the path information based on the data already bound to this group: .attr("d", arc); // A centroid is the calculated center point of any shape, whether that shape is regular (like a square) or highly irregular (like an outline of the state of Maryland). arc.centroid() is a super-helpful function that calculates and returns the center point of any arc. We translate each text label element to each arc’s centroid, and that’s how we get the text labels to float right in the middle of each wedge. // console.log(pie(dataset)[0]); console.log(arc.centroid(pie(dataset)[0])); arcs.append("text") .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("text-anchor", "middle") .text(function(d) { return d.value; }); </script> </body> </html>
https://d3js.org/d3.v4.min.js