D3 pie (donut) chart label outside of each arc

4.7k Views Asked by At

I am new to D3 and I've got my donut chart however I can't get arc labels outside of each arc.

I want to get something like labels in purple in http://bl.ocks.org/Guerino1/2295263, but I can't get it working for my donut chart.

I am using following code to append each arc's label but it seems like arc.centroid not working as expected.

        var arcs = vis.selectAll("g.slice")
    arcs.append("svg:text")
      .attr("transform", function(d, i) { //set the label's origin to the center of the arc
        d.outerRadius = svgOuterRadius + 40; // Set Outer Coordinate
        d.innerRadius = svgOuterRadius + 35; // Set Inner Coordinate
        return "translate(" + arc.centroid(d) + ")";
      })
      .attr("text-anchor", "middle") //center the text on it's origin
      .style("fill", "Purple")
      .style("font", "bold 14px Arial")
      .text(function(d, i) { return 'label'+i; }); //get the label from our original

Here is my JSfiddle:

I really appreciate it in advance.

1

There are 1 best solutions below

2
On

The basic problem is that your arc path segments are translated and you don't take that translation into account when adding the labels. If you look at the example you've linked to, you'll see that the path segments are added without any translation, which means that the text elements can be added without an additional offset.

To fix simply take the offset into account:

arcs.append("svg:text")
      .attr("transform", function(d, i) { //set the label's origin to the center of the arc
          var c = arc.centroid(d);
        return "translate(" + (svgWidth/2 + c[0]) + "," + (svgHeight/2 + c[1]) + ")";
})
// etc

Full example here.