score:1

Accepted answer

Since d3.scale.category10() operates in a first-come first-served basis, that is, it adds values to the domain as new data comes in, you just need to pass the name in the same order that you painted the circles.

However, for this to work, you'll have to change your function color():

function color(d) {
    return d.name;
}

Now, both the circles and the legends will have the same domain in the color scale.

Now, create the legends:

var legendGroup = svg.append("g")
    .attr("transform", "translate(600,50)");

var legend = legendGroup.selectAll(".legend")
    .data(SPX.map(d => d.name))
    .enter()
    .append("g")
    .attr("transform", (d, i) => "translate(0," + 20 * i + ")")

var legendRects = legend.append("rect")
    .attr("width", 10)
    .attr("height", 10)
    .attr("fill", d => colorScale(d));

var legendText = legend.append("text")
    .attr("x", 14)
    .attr("y", 8)
    .text(d => d);

Here is your fiddle, I put the legends in the top-right corner: http://jsfiddle.net/8yd04e0p/


Related Query