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

拜拜、爱过 提交于 2019-12-22 18:06:22

问题


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.


回答1:


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); });


来源:https://stackoverflow.com/questions/18874877/how-do-i-color-labels-for-my-pie-chart-in-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!