簡體   English   中英

如何在D3中為餅圖標記標簽?

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

我從以下示例開始:

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()");

這使所有標簽成為我數組中的第一種顏色。 但是,我需要每個標簽在數組中使用不同的顏色。 我只是不確定如何訪問標簽,所以我可以循環瀏覽並更改顏色。

只需添加與圓弧相同的填充參數即可,例如

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