0

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.

Andrey Morozov
  • 7,839
  • 5
  • 53
  • 75
user2975436
  • 235
  • 5
  • 12

1 Answers1

1

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.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thank you so much, It looks great. Can I ask you one more thing? I wanted the each label to be outside of each arc however adding d.outerRadius = + 50; d.innerRadius = + 45; before arc.centroid(d) did not help. Do you know how I can get each label position outside of each arc? – user2975436 Dec 21 '13 at 01:05
  • [This question](http://stackoverflow.com/questions/8053424/label-outside-arc-pie-chart-d3-js) should help. – Lars Kotthoff Dec 21 '13 at 10:20