Generate 16 Colors Based On Values From 3 Colors
I'm trying to write function i n javascript, which can generate colors between three colors based on a given value. Heres an explanation: There are two colors : #0a0000, #ffaa03 &
Solution 1:
It seems to me that the scale you need is a simple linear scale, with the domain as the extent of your data and the range as ["#ffffd5", "#0a0000"]
.
Here is an example, with the data unsorted (as you mentioned):
const fakeData = d3.range(16).map(_ => d3.randomUniform(30)());
const scale = d3.scaleLinear()
.domain(d3.extent(fakeData))
.range(["#ffffd5", "#0a0000"]);
d3.select("body").selectAll(null)
.data(fakeData)
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
display: inline-block;
margin-right: 4px;
width: 20px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
And here with the data sorted:
const fakeData = d3.range(16).map(_ => d3.randomUniform(30)()).sort((a, b) => a - b);
const scale = d3.scaleLinear()
.domain(d3.extent(fakeData))
.range(["#ffffd5", "#0a0000"]);
d3.select("body").selectAll(null)
.data(fakeData)
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
display: inline-block;
margin-right: 4px;
width: 20px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Finally, the image you posted doesn't match the colours you described (from #ffffd5
to #0a0000
). That said, you could alternatively use a sequential scale with another colour array, for instance:
const fakeData = d3.range(16).map(_ => d3.randomUniform(30)()).sort((a, b) => a - b);
const scale = d3.scaleSequential(d3.interpolateReds)
.domain(d3.extent(fakeData));
d3.select("body").selectAll(null)
.data(fakeData)
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
display: inline-block;
margin-right: 4px;
width: 20px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Post a Comment for "Generate 16 Colors Based On Values From 3 Colors"