D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
DDDDDanica
Full window
Github gist
Pie chart with labels
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v3.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 data = [ {name: "A", val: 11975}, {name: "B", val: 5871}, {name: "C", val: 8916} ]; var w = 600, h = 400, r = Math.min(w, h) / 2, labelr = r + 30, // radius for label anchor color = d3.scale.category20(), donut = d3.layout.pie(), arc = d3.svg.arc().innerRadius(r*.6).outerRadius(r); var vis = d3.select("body") .append("svg:svg") .data([data]) .attr("width", w + 150) .attr("height", h); var arcs = vis.selectAll("g.arc") .data(donut.value(function(d) { return d.val })) .enter().append("svg:g") .attr("class", "arc") .attr("transform", "translate(" + (r + 30) + "," + r + ")"); arcs.append("svg:path") .attr("fill", function(d, i) { return color(i); }) .attr("d", arc); arcs.append("text") .attr("text-anchor", "middle") .attr("x", function(d) { var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2; d.cx = Math.cos(a) * (r - 45); return d.x = Math.cos(a) * (r+30); }) .attr("y", function(d) { var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2; d.cy = Math.sin(a) * (r - 45); return d.y = Math.sin(a) * (r + 30); }) .text(function(d) { return d.value.toFixed(2); }) .each(function(d) { var bbox = this.getBBox(); d.sx = d.x - bbox.width/2 - 2; d.ox = d.x + bbox.width/2 + 2; d.sy = d.oy = d.y + 5; }); arcs.append("path") .attr("class", "pointer") .style("fill", "none") .style("stroke", "black") .attr("d", function(d) { console.log(d); if(d.cx > d.ox) { return "M" + d.sx + "," + d.sy + "L" + d.ox + "," + d.oy + " " + d.cx + "," + d.cy; } else { return "M" + d.ox + "," + d.oy + "L" + d.sx + "," + d.sy + " " + d.cx + "," + d.cy; } }); </script> </body>
https://d3js.org/d3.v3.min.js