Dinosaurius
Dinosaurius

Reputation: 8628

How to add legend to the chart?

How can I add legend to the chart (see fiddle)? I tried to define the legend as follows, but then the chart disappears (see this fiddle).

var height = 900, width = 900;
var gridSize = Math.floor(width / 42);
var legendElementWidth = gridSize*2;

var legend = svg.selectAll(".legend")
              .data([0].concat(colorScaleDomain.quantiles()), function(d) { return d; });

legend.enter().append("g")
  .attr("class", "legend");

legend.append("rect")
.attr("x", height)
.attr("y", function(d, i) { return legendElementWidth * (i-0.5); })
.attr("width", gridSize / 2 )
.attr("height", legendElementWidth)
.style("fill", function(d, i) { return colors[i]; });

legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d) + "%"; })
.attr("x", (height) + gridSize)
.attr("y", function(d, i) { return legendElementWidth*i; } );

legend.exit().remove();

Upvotes: 1

Views: 282

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

This is a list of the problems:

  1. There is no colorScaleDomain.quantiles(). It should be colorScale.quantiles() instead.

  2. The order of the elements is very important in an SVG, which has no z index. So, your legends...

    legend.enter().append("g")
        .attr("class", "legend");
    

...should come after the drawing code for the chart. But that step can even be ignored, because of the third problem:

  1. Your legends are outside the SVG. I corrected that with:

    var svg = d3.select("body").append("svg")
        .attr("width", diameter + 200)//adding some space in the SVG
    

And some more magic numbers in the legends code. Change them accordingly (magic numbers are not a good practice in most situations).

Here is your updated fiddle: https://jsfiddle.net/hsq05oq9/

Upvotes: 2

Related Questions