How to correctly add labels to the d3 pie chart?

I made a pie chart using d3 js and I want to add labels to the every path.

I wrote some code:

var labels = svg.selectAll('path').insert("text").data(pie(data))
       .text( function (d) { return d.value; })
       .attr("font-family", "sans-serif")
       .attr('x', 0)           
       .attr('y', 0)
       .attr("font-size", "12px")
       .attr("fill", "red");

but there is no visible result, only I can see that there are new text elements in the Chrome developer tools.

Result and Chrome dev tools

How I need to change my code to see all labels on the pieces of my pie chart?

Upvotes: 2

Views: 4809

Answers (1)

Mikhail Shabrikov
Mikhail Shabrikov

Reputation: 8509

You cannot append text node as a child for path. You should group these elements with g tag and append paths and texts as a child for g elements.

// append "g" it is a container for your slice and label
var arcs = vis.selectAll("g.slice")
  .data(pie)
  .enter()
  .append("g")
  .attr("class", "slice");

// draw slice of pie chart
arcs.append("path")
    .attr("fill", function(d, i){
        return color(i);
    })
    .attr("d", function (d) {
        return arc(d);
    });

// draw label
arcs.append("text")
  .attr("transform", function(d){
      d.innerRadius = 0;
      d.outerRadius = r;
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text( function(d, i) {
      return data[i].label;}
    );

In this case, your structure will look like:

<g>
 <path d=...></path>
 <text>some text</text>
</g>
<g>
 <path d=...></path>
 <text>some text</text>
</g>
...

Check working example:

var w = 280;
var h = 280;
var r = h/2;
var color = d3.scale.category20c();

var data = [{"label":"Category A", "value":20}, 
		          {"label":"Category B", "value":50}, 
		          {"label":"Category C", "value":30}];

var vis = d3.select('body').append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")");
var pie = d3.layout.pie().value(function(d){return d.value;});

var arc = d3.svg.arc().outerRadius(r);

var arcs = vis.selectAll("g.slice")
  .data(pie)
  .enter()
  .append("g")
  .attr("class", "slice");

arcs.append("path")
    .attr("fill", function(d, i){
        return color(i);
    })
    .attr("d", function (d) {
        return arc(d);
    });

arcs.append("text")
  .attr("transform", function(d){
			d.innerRadius = 0;
			d.outerRadius = r;
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text( function(d, i) {
      return data[i].label;}
		);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 6

Related Questions