简体   繁体   English

如何在D3中为饼图标记标签?

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

I started out with the following example: 我从以下示例开始:

http://jsfiddle.net/nrabinowitz/GQDUS/ 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. 我只是不确定如何访问标签,所以我可以循环浏览并更改颜色。

Just add the same fill argument that was used for the arcs eg 只需添加与圆弧相同的填充参数即可,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM