Vaslo
Vaslo

Reputation: 511

Return individual value from a D3 color range to create legend

I have code for 5 colors:

var color = d3.scaleQuantize()
    .range([
        'rgb(237,248,233)',
        'rgb(186,228,179)',
        'rgb(116,196,118)',
        'rgb(49,163,84)',
        'rgb(0,109,44)'
    ]);

I want to grab each one of those values in order to color a legend.

I'm trying things like this but it's not working:

.style('fill', function (d, i) {
    return color.range([0]);
});

How do I reference each item in the color range so I can color a block of legend that way?

Thanks!

Edit: Sorry I left the console.log piece there that I was testing the code with, now corrected.

Upvotes: 0

Views: 127

Answers (2)

Umesh Markande
Umesh Markande

Reputation: 309

you can use function variable of i, these i variable follows the sequence. For example

.style("fill", function (d,i) {
                    return color(i);//or color.range(i);

Upvotes: 1

Vaslo
Vaslo

Reputation: 511

I think I figured it out. d3.scaleQuantize() returns a value if you input a number in parentheses. However, just doing color like it was a regular array gave me each color individually, which could be fed into the legend.

.style("fill", function (d, i) {return d};)

Upvotes: 0

Related Questions