moodygeek
moodygeek

Reputation: 127

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

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 e.g Class A, B ..

Please assist

Upvotes: 1

Views: 215

Answers (1)

Gilsha
Gilsha

Reputation: 14591

In d3, the second parameter of the function is the index of the element. 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"}

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

Upvotes: 1

Related Questions