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

JS *_*oob 2 javascript svg d3.js pie-chart donut-chart

我从以下示例开始:

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

我正在尝试使每个圆弧的标签成为圆弧的颜色。

我已经到了它为所有标签涂上相同颜色的地方。但是我现在知道如何访问每个标签并更改颜色。

在我的代码中,我对最后一行做了以下操作:

    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()");
Run Code Online (Sandbox Code Playgroud)

这使所有标签成为我数组中的第一种颜色。但是,我需要每个标签在数组中使用不同的颜色。我只是不确定如何访问标签,所以我可以循环浏览并更改颜色。

Rob*_*son 5

只需添加与圆弧相同的填充参数即可,例如

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); });
Run Code Online (Sandbox Code Playgroud)