Reputation: 37
I'm trying to color each bar with a specified custom color. I've done this with real data up until this point by putting in a domain with data names and putting the colors in the range like this:
var colorBar = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E", "F", "G", "H"])
.range(['#2fbcfc','#02a1e9','#6771DC', '#845EC2','#AD5EBA','#D65DB1', '#DC67AB', '#FF6F91']);
Then I would just call it like this:
.style("fill", function(d) { return colorBar(d.name); })
I don't know how to call it now that the data is random or what to put in the domain.
Here's the codepen: https://codepen.io/priglantonio/pen/VwZPBeR
Upvotes: 0
Views: 152
Reputation: 331
If you want the color of each bar to be based on its index, you could just modify your colorBar
function to work with the index and pass that instead of the data:
var dataset = [...some random numbers];
var colorBar = d3.scale.ordinal()
.domain(d3.range(dataset.length)) // returns [0, 1, 2, 3..., <dataset.length - 1>]
.range(['#2fbcfc','#02a1e9','#6771DC', '#845EC2','#AD5EBA','#D65DB1', '#DC67AB', '#FF6F91']);
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
.attr("class", "bar")
.style("background-color", (_, i) => colorBar(i));
Upvotes: 1