Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert a color scale in d3.js

Tags:

d3.js

Is it possible to create a scale in d3 with a color domain and a number range?

I tried the following:

  var colorScale = d3.scale.linear().range(["red", "white"]).domain([3, 9.5])
  console.log('cs:', colorScale(4));
  console.log('cs:', colorScale.invert(colorScale(4)));

But the output isn't very encouraging:

cs: #ff2727
cs: NaN

Is this an impossible task or am I doing something wrong?

like image 894
juniper- Avatar asked Dec 12 '25 16:12

juniper-


1 Answers

According to the documentation:

Note: the invert operator is only supported if the output range is numeric! D3 allows the output range to be any type; under the hood, d3.interpolate or a custom interpolator of your choice is used to map the normalized parameter t to a value in the output range. Thus, the output range may be colors, strings, or even arbitrary objects. As there is no facility to "uninterpolate" arbitrary types, the invert operator is currently supported only on numeric ranges.

So no, you can't do this.

like image 189
Lars Kotthoff Avatar answered Dec 16 '25 12:12

Lars Kotthoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!