D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
manojwajekar
Full window
Github gist
Pie_Chart_With%
Built with
blockbuilder.org
<!DOCTYPE html> <meta charset="utf-8"> <style> .arc text { font: 12px sans-serif; text-anchor: middle; font-weight: bold; } .arc path { stroke: #fff; } </style> <svg width="960" height="500"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"), radius = Math.min(width, height) / 2.25, g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var color = d3.scaleOrdinal(['#67bf5c','#ff9e4a','#6dccda','#ad8bc9','#ed665d', '#cdcc5d', '#a8786e', '#729ece', '#a2a2a2','#ed97ca']); var pie = d3.pie() .sort(null) .value(function(d) { return d.total; }); var path = d3.arc() .outerRadius(radius - 10) .innerRadius(0); var label = d3.arc() .outerRadius(radius - 40) .innerRadius(radius - 40); var percentageFormat = d3.format(".2%",); /* d3.csv("data.csv", function(d) { d.population = +d.population; return d; }, function(error, data) { if (error) throw error;*/ d3.json("data.json", function(error, data) { var tots = d3.sum(data, function(d) { return d.total; }); data.forEach(function(d) { // d.leads_intended_storage_duration_tiers = (d.leads_intended_storage_duration_tiers); d.total = +d.total; d.percentage = d.total / tots; }); var arc = g.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc"); arc.append("path") .attr("d", path) .attr("fill", function(d) { return color(d.data.leads_intended_storage_duration_tiers); }); arc.append("text") .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; }) .attr("dy", "0.35em") .style("text-anchor", "middle") .text(function(d) { return d.data.leads_intended_storage_duration_tiers; }) arc.append("text") .attr("transform", function(d) { var _d = path.centroid(d); _d[0] *= 2.3; //multiply by a constant factor _d[1] *= 2.3; //multiply by a constant factor return "translate(" + _d + ")"; }) .attr("dy", ".50em") .style("text-anchor", "middle") .text(function(d) { console.log("d is", d); return percentageFormat(d.data.percentage);}) }); </script>
https://d3js.org/d3.v4.min.js