Reputation: 6685
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
.
Upvotes: 4
Views: 1653
Reputation: 61
Top comment works perfect, but if anybody is using d3 v3 then this would work as well.
var colors = d3.scale.linear().domain([0, 3]).range(["yellow", "red"]);
colors(0); // Yellow
colors(3); // Red
Upvotes: 0
Reputation: 102219
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>
Upvotes: 5
Reputation: 1204
Use d3.rgb.brighter(k)
or d3.rgb.darker(k)
from d3 documentation.
Like this: let red = d3.rgb("red")
, which gives red the rgb value of d3 representation of red (r=255). Then, red.darker(0.5)
give a darker red (r=213):
let red = d3.rgb("red");
let darker = red.darker(0.5);
console.log(darker.toString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Note: the brighter
and darker
can be applied to other type of color (hsl, rgba,...)
Upvotes: 4