Search code examples
colorsd3.jsrangescale

rounded values for color in d3 scale


what i would like to do is to create not a range of colors for an output value, but a hard color based on the input. ie say i have:

color = d3.scale.linear().domain( [0,1,10] ).range( [ 'green', 'orange', 'red' ] )
d3.range(0,10).forEach( (d) ->
    console.log d + ' ' + color(d)
)

this would create a range of colors between orange and red. however, i would like:

0   = green
1-9 = orange
10  = red

in addition i would to be able to handle the NaN case such that it's gray.

i was playing with ordinal but i don't particularly want to specify all of the numbers for the domain (as my input may be a float).

how do i do this?


Solution

  • Use a threshold scale:

    color = d3.scale.threshold()
              .domain([1, 10])
              .range(['green', 'orange', 'red'])
    
    > color(0)
    "green"
    > color(1)
    "orange"
    > color(8)
    "orange"
    > color(10)
    "red"