score:3

Accepted answer

You need to use colors rather than dataset as parameter for the .data() of your legend. In order for that to work, colors has to be an array rather than an object:

var colors = [ ["Local", "#377EB8"],
               ["Global", "#4DAF4A"] ];

The code for creating the legend then becomes:

var legendRect = legend.selectAll('rect').data(colors);

legendRect.enter()
    .append("rect")
    .attr("x", w - 65)
    .attr("width", 10)
    .attr("height", 10);

legendRect
    .attr("y", function(d, i) {
        return i * 20;
    })
    .style("fill", function(d) {
        return d[1];
    });

var legendText = legend.selectAll('text').data(colors);

legendText.enter()
    .append("text")
    .attr("x", w - 52);

legendText
    .attr("y", function(d, i) {
        return i * 20 + 9;
    })
    .text(function(d) {
        return d[0];
    });

Cf the updated fiddle.


Related Query

More Query from same tag