Label outside arc (Pie chart) d3.js

3,178 views
Skip to first unread message

Ibe Vanmeenen

unread,
Nov 8, 2011, 3:14:45 PM11/8/11
to d3-js
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.centriod

arcs.append("svg:text")
.attr("transform", function(d) { return "translate(" +
arc.centroid(d) + ")"; })
.attr("text-anchor", "middle")

Who can help me with this?
Thanks in andvanced!

Ian Johnson

unread,
Nov 10, 2011, 10:39:24 PM11/10/11
to d3...@googlegroups.com
I've hacked a little function to do this:

function place_label(d, r)
{
        //figure out the center point of the arc, at radius r
        ao = -Math.PI / 2 ;
        aa = (d.startAngle + d.endAngle) / 2 ;
        tx = Math.cos(aa + ao);
        ty = Math.sin(aa + ao) ;
        tx *= r;
        ty *= r;
        return {"x": tx, "y": ty }
}

just make r bigger than the radius you used for your pie chart
pass in the d element for the arc you are getting the centroid from

this is basically the centroid function augmented slightly
--
Ian Johnson

Ibe Vanmeenen

unread,
Nov 15, 2011, 10:38:04 AM11/15/11
to d3-js
Thanks! :-)

I just found an other solution :-)
I created a second arc with a bigger radius and used it to position my
labels.

///// Arc Labels /////
// Calculate position
var pos = d3.svg.arc().innerRadius(r + 20).outerRadius(r + 20);

// Place Labels
arcs.append("svg:text")
.attr("transform", function(d) { return "translate(" +
pos.centroid(d) + ")"; })
.attr("dy", 5)
.attr("text-anchor", "middle")
.attr("fill", function(d, i) { return colorL(i); }) //Colorarray
Labels (alt: .attr("fill", "#FFF")
.attr("display", function(d) { return d.value >= 2 ? null :
"none"; }) //Don't show if value is smaler than 2
.text(function(d, i) { return d.value.toFixed(0) + "%"}); //
Waarden inplaatsen

Ravi Prakash

unread,
Apr 4, 2017, 8:37:12 AM4/4/17
to d3-js
Can you please create a jsfiddle for it. 

Ravi Prakash

unread,
Apr 4, 2017, 8:39:06 AM4/4/17
to d3-js
I need a graph just like the attached screenshot.
chart sample.png
Reply all
Reply to author
Forward
0 new messages