bruh bruh - 2 months ago 37
Javascript Question

VueJS Dynamic Bar Chart Colors

Given a bar graph with 2 data sets. How can I give each bar its own color?

svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.style("fill", function(d,i) { console.log(i.fill) } // <- first red, second blue

Answer

I'm too lazy to set up a demo for what I think might work, but I imagine you want an array of colors like:

var colors = ['red', 'blue'];

then in your callback for fill you can do like this:

return colors[i % colors.length];

If I'm correct in assuming i is an index for the bar you're on.