D3 scaleLinear() returns rgb value although the range is in hex values

Viewed 926

d3.scaleLinear() returns an rgb string value although the range is mapped with hex values. Is there something incorrect in my usage?

const value = 0;
col = d3.scaleLinear().domain([0, 16000]).range(["#ffdc00","#ffa900"]);
console.log(col(value));
//returns rgb(255, 220, 0)
1 Answers

d3-scale relies on d3-interpolate, which uses d3.interpolateRgb by default whenever colors are detected (source):

If b is a color or a string coercible to a color, use interpolateRgb.

As stated in the documentation for d3.interpolateRgb:

The return value of the interpolator is an RGB string.

The behaviour is therefore normal, and the provided code sample is perfectly fine.

RGB strings are equivalent to their hexadecimal representation, so they may be used directly.

If the use case requires to have a hexadecimal string, the function color.formatHex from d3-color can be used, as illustrated in the snippet below:

const value = 0;
col = d3.scaleLinear().domain([0, 16000]).range(["#ffdc00","#ffa900"]);

let rgbValue = col(value)

console.log('rgb string:', rgbValue);

console.log('hex string:', d3.color(rgbValue).formatHex());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.min.js"></script>

Related