tomtomtom
tomtomtom

Reputation: 1522

D3.js ~ placing rectangles with for loop and coloring them

I need to set up the color legend for a scatterplot. I already set up the scale and it's working on the dots in the scatterplot, however what i want to do now is to draw a little square for each color, filled with the color itself, to show the legend of the diagram. Something like this at the start of my graph: enter image description here

I tried to set up the function to draw them accordingly but failed, here's what I tried:

var colore = d3.scale.ordinal()
    .domain(d3.extent(dataset, function (d) { return d.Peso; }))
    .range(["#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]);

and the function to draw the squares:

svg.selectAll("rect")
    .data(colore.range())
    .enter()
    .append("rect")
    .attr("fill", function (i) { return colore(i); })
    .attr("x", function (i) {for (i=1; i <= colore.range().length; i++) 
        { return (i * 12) + "px"; }
        })
    .attr("y", margin - 8 + "px")
    .attr("width", 8 + "px")
    .attr("height", 8 + "px");

This appends to the svg element 8 squares, but stacked onto eachother, like so (the red one): enter image description here

So I don't know how to correct my for functions, which I assume are where the errors happen. Thanks in advance for any help!

Upvotes: 2

Views: 2033

Answers (1)

mdml
mdml

Reputation: 22882

The problem is you're not using the data bound to each rectangle, but instead looping over all the colors each time. Try something like this:

svg.selectAll("rect")
    .data(colore.range()).enter()
    .append("rect")
    .attr("fill", function (color){ return color; })
    .attr("x", function (color, index){ return (index * 12) + "px"; })
    .attr("y", margin - 8 + "px")
    .attr("width", 8 + "px")
    .attr("height", 8 + "px");

The key thing to note is that if you can pass an attribute a function that takes an Object and an index as arguments that will then get applied to each datum. Using this approach, I get this:

example output

Upvotes: 3

Related Questions