Built with blockbuilder.org
Last active
April 5, 2017 10:04
-
-
Save DDDDDanica/661e8bb2ddd79b7bc4cf790ef4f1f648 to your computer and use it in GitHub Desktop.
Pie chart with labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment