在 d3.js 中反转色标

Invert a color scale in d3.js

是否可以在 d3 中创建具有色域和数字范围的比例尺?

我尝试了以下方法:

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

但输出不是很令人鼓舞:

cs: #ff2727
cs: NaN

这是不可能完成的任务还是我做错了什么?

根据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.

所以不,你不能这样做。