How can I get different shades of color for single color by using d3.js?
For example:
colorScale('myId') => 'red' and colorScale(red)(10) => dark red & colorScale(red)(1) => light red.
Given your description of the desired outcome, I highly doubt that you want shades: technically speaking, shades are mixtures of a given colour with black, reducing its lightness.
So, assuming that you really want shades, the task can be done with a simple linear scale going from "red" to "black" and using [0, 40] as the domain (here using D3 v5.8 new constructor):
const scale = d3.scaleLinear([0,40], ["red", "black"])
You can also set a interpolator if you want to change some values, as the gamma:
const scale = d3.scaleLinear([0,40], ["red", "black"])
.interpolate(d3.interpolateRgb.gamma(1.9));
Here is the demo:
const scale = d3.scaleLinear([0, 40], ["red", "black"])
.interpolate(d3.interpolateRgb.gamma(1.9));
d3.select("body").selectAll(null)
.data(d3.range(41))
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 2px;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
By using more different values in the domain we can create a gradient with the shades (this is just a demo, don't append 500 divs for creating a gradient!):
const scale = d3.scaleLinear([0, 500], ["red", "black"])
.interpolate(d3.interpolateRgb.gamma(1.9));
d3.select("body").selectAll(null)
.data(d3.range(501))
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
display: inline-block;
width: 1px;
height: 40px;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With