D3.js how to create color scales - d3.scaleLinear, d3.scaleOrdinal, d3.interpolate, d3.scaleSequential, d3.scaleThreshold
d3-scale
d3.scaleLinear
This method uses linear scale conversion. It is generally used for coordinate conversion in graphs, but it can also be used for colors.
var color = d3.scaleLinear()
.domain([0, 10])
.range(["red", "blue"]);
d3.scaleLinear sets a function that converts the range specified by domain into the range specified by range and returns the result. A function is assigned to color, and you use it by passing a value within the range specified by domain, as shown below.
color(2)
It linearly converts and returns RGB values according to the input number. The following chart is an example where "red" and "blue" are specified for range. The numbers below the chart are the values input into scale.
You can also set three or more colors as follows:
var color = d3.scaleLinear()
.domain([0, 5, 10])
.range(["red", "yellow", "blue"]);
d3.scaleOrdinal
This repeatedly applies the array entered in range.
var color = d3.scaleOrdinal()
.range(["red", "white", "green"]);
d3.interpolate
If you simply want linear interpolation between two colors, use d3.interpolate.
The difference from d3.scaleLinear is that the input value is set in the range from 0.0 to 1.0.
var color = d3.interpolate("brown", "steelblue");
d3.scaleSequential
This linearly converts the range set in domain to the range from 0.0 to 1.0 and passes it to a function.
The output value is determined by the function. For example, you can use d3.interpolate to create a scale that combines multiple colors.
var i0 = d3.interpolate("brown", "white");
var i1 = d3.interpolate("white", "steelblue");
var color = d3.scaleSequential(
function (t) {
return (t < 0.5) ? i0(2 * t) : i1((t - 0.5) * 2);
})
.domain([0, 10]);
d3.scaleThreshold
This determines colors by threshold values. Because the array entered in domain becomes the thresholds, range needs one more array element than domain.
var color = d3.scaleThreshold()
.domain([0, 1])
.range(["red", "white", "green"]);