I’m new to d3.js and I”m trying to make a Pie-chart with it.
I have only one problem: I can’t get my labels outside my arcs…
The labels are positioned with arc.centroid
arcs.append("svg:text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
Who can help me with this?
I can solve that problem – with trigonometry :).
See fiddle: http://jsfiddle.net/nrabinowitz/GQDUS/
Basically, calling
arc.centroid(d)returns an[x,y]array. You can use the Pythagorean Theorem to calculate the hypotenuse, which is the length of the line from the center of the pie to the arc centroid. Then you can use the calculationsx/h * desiredLabelRadiusandy/h * desiredLabelRadiusto calculate the desiredx,yfor your label anchor:The only downside here is that
text-anchor: middleisn’t a great choice anymore – you’d be better off setting thetext-anchorbased on which side of the pie we’re on: