Search code examples
javascriptsvgd3.jspie-chartdonut-chart

How do I color labels for my pie chart in D3?


I started out with the following example:

http://jsfiddle.net/nrabinowitz/GQDUS/

I am trying to get the labels for each arc to be the color of the arc.

I have gotten it to where it colors all the labels the same color. But I do now know how to access each individual label and change the color.

In my code I have done the following for the last line:

    arcs.append("svg:text").attr("transform", function (d){var c = arc.centroid(d); x =   c[0]; y = c[1]; h = Math.sqrt(x*x + y*y);  return "translate(" + (x/h * 100) + ',' + (y/h * 90) + ")";}).text(function(d){return Math.round((d.data/total)*100)+"%";}).attr("text-anchor","middle").attr("fill","color_data.pop()");

This makes all the labels the first color in my array. However I need each label to be a different color in the array. I am just not sure how to access the labels so I can loop through and change the color.


Solution

  • Just add the same fill argument that was used for the arcs e.g.

    arcs.append("svg:text")
        .attr("transform", function(d) {
            var c = arc.centroid(d),
                x = c[0],
                y = c[1],
                // pythagorean theorem for hypotenuse
                h = Math.sqrt(x*x + y*y);
            return "translate(" + (x/h * labelr) +  ',' +
               (y/h * labelr) +  ")"; 
        })
        .attr("dy", ".35em")
        .attr("fill", function(d, i) { return color(i); })
        .attr("text-anchor", function(d) {
            // are we past the center?
            return (d.endAngle + d.startAngle)/2 > Math.PI ?
                "end" : "start";
        })
        .text(function(d, i) { return d.value.toFixed(2); });