Reputation: 889
I'm diving into d3 but be still an absolute beginner so bear with me if this is an obvious one.
I have a line graph with multiple lines (actually about ~150) which I would like to color in a range between lets say red to blue.
I managed to hard code the color of the lines with something like
var color = d3.scaleOrdinal()
.range(["#FF0000", "#0000FF"]);
but I obviously don't want to do that for 150 different color values. Is there a straight forward way to achieve this?
Upvotes: 1
Views: 511
Reputation: 102174
You didn't specify how you're going to choose each line. I'm assuming it's by their indices, not by any bound datum. That being the case, a simple linear scale...
const scale = d3.scaleLinear()
.domain([0, 149])
.range(["#FF0000", "#0000FF"]);
...can work, to which you'll pass the indices.
Here is a demo:
const scale = d3.scaleLinear()
.domain([0, 149])
.range(["#FF0000", "#0000FF"]);
d3.select("body").selectAll(null)
.data(d3.range(150))
.enter()
.append("div")
.style("background-color", (_, i) => scale(i))
div {
width: 10px;
height: 10px;
margin-right: 2px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
However, if you do want to use an ordinal scale, for any reason, you don't need to manually create each colour in the range. You can use a D3 interpolator to create the array, like this:
const interpolator = d3.interpolateRgb("#FF0000", "#0000FF");
const colors = d3.range(150).map(t => interpolator(t / 149));
Then, you just need to pass that array to your ordinal scale's range:
var color = d3.scaleOrdinal()
.range(colors);
Here is the demo:
const interpolator = d3.interpolateRgb("#FF0000", "#0000FF");
const colors = d3.range(150).map(t => interpolator(t / 149));
console.log(colors)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Upvotes: 2