简体   繁体   English

D3.js为带有内圈的甜甜圈图赋予图例

[英]D3.js Giving a legend to a donut chart with inner rings

I am trying to add a properly labelled legend to a donut chart with multiple rings. 我试图将带有正确标记的图例添加到具有多个环的甜甜圈图中。 I have the updated code on the plunker here : donut chart 我在这里的pl子上有更新的代码: 甜甜圈图

Here is the code which I use for adding the legend: 这是我用来添加图例的代码:

 var legend = chart1.selectAll(".legend")
     .data(color.domain().slice())//.reverse())
     .enter().append("g")
     .attr("class","legend")
     .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

legend.append("rect")
    .attr("x", 190)
    .attr("y", -(margin.top) * 7 - 8)
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", color);

legend.append("text")
    .attr("x", margin.right * 7)
    .attr("y", -(margin.top) * 7)
    .attr("dy", ".35em")
    .text(function(d,i) { return d; });

As you would notice on the chart that the legend is numbered from 0 to 5, but what I want is for the legend to be labelled based on the classes used to draw the chart eg Class A, B .. 正如您在图表上注意到的那样,图例的编号从0到5,但是我想要的是根据用于绘制图表的类(例如A,B等)对图例进行标记。

Please assist 请协助

In d3 , the second parameter of the function is the index of the element. d3 ,函数的第二个参数是元素的索引。 So you can directly get any property from the data array by using this index. 因此,您可以使用此索引直接从数据数组中获取任何属性。

Eg. 例如。

data[0] -> {"Class":"Class A","Actual_Class":"495","Predicted_Class":"495","Accuracy":"100"} data [0]-> {"Class":"Class A","Actual_Class":"495","Predicted_Class":"495","Accuracy":"100"}

So try this code. 因此,请尝试此代码。

legend.append("text")
      .attr("x", margin.right * 7)
      .attr("y", -(margin.top) * 7)
      .attr("dy", ".35em")
      .text(function(d,i) { 
         return data[i].Class; 
       });

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

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