Minh
Minh

Reputation: 2300

d3: Color Range with an array with more than 2 colors

I'm trying to shade a layer in a map (using MapBox) depending on the value of the properties in a .json file. However the code only works with 2 color values passed through. A snippet of my color coding is below.

  var color =
    d3.scale.linear()
    .domain(range)
    .range([#F0F0D0', '#228B22]);

It would fail if I do this

  var color =
    d3.scale.linear()
    .domain(range)
    .range(['930F16', '#F0F0D0', '#228B22]);

The map will display the range of the first two colors.

How would I extend if I wanted to do a range of colors beyond two? For instance, if I wanted the lower end to be red, the middle quantiles to be white, and the top quantiles to be green?

Upvotes: 3

Views: 3123

Answers (2)

Stephen Thomas
Stephen Thomas

Reputation: 14053

The number of elements in the range() input array is truncated to match the number of elements in the domain(). To use three colors, you'll need to set the scale's domain() to have three elements as well. That's what you're (confusingly) calling range (the variable) in the snippet.

var color =
    d3.scale.linear()
        .domain([d3.min(data), (d3.max(data)-d3.min(data))/2, d3.max(data)])
        .range(['#930F16', '#F0F0D0', '#228B22']);

Upvotes: 1

David
David

Reputation: 7285

Something like this?

var color = d3.scale.linear()
    .domain([-1, 0, 1])
    .range(['#930F16', '#F0F0D0', '#228B22']);

This will interpolate between '#F0F0D0' and '#930F16' for negative values, and '#F0F0D0' and '#228B22' for positive values.

Hope it helps!

Upvotes: 2

Related Questions