Mr.Roboto Mr.Roboto - 4 months ago 19
Javascript Question

2 arrays one of values one of colors make D3 bar chart have color at same index of value

I have 2 Arrays:

values = [1,2,3,4,5,4,7,2,9,10];
colors = ['red','red','blue','blue,'green','green','orange','orange','pink,'pink];

I am trying to build a D3 Bar chart where each bar has height of 10*the value and corresponds to the color that has the same index as the value.

This is what I have so far:"body").selectAll("div")
.attr("class", "bar")
.style("fill", function(d) {
return colors[values.indexOf(d)];

However, say we have a duplicate value then it will return the wrong color. I also tried to create a JSON from the 2 arrays and then pass that in as the data but I was having trouble with this. What is the best way to do the above? Thanks!


Since you only want each bar having a colour that...

corresponds to the color that has the same index as the value

You just need to access the array colors using the index of each bar:

.attr("fill", function(d,i){ return colors[i]});

Here is a working example (using the width as 10x the value, not the height, for simplicity):

values = [1,2,3,4,5,4,7,2,9,10];
colors = ['red','red','blue','blue','green','green','orange','orange','pink','pink'];

var width = 400, height = 400;

var svg ="body")
	.attr("width", width)
	.attr("height", height);
var bars = svg.selectAll(".myBars")
bars.attr("x", 10)
	.attr("y", function(d,i){ return 10 + i*40})
	.attr("width", function(d){ return d*10})
	.attr("height", 30)
	.attr("fill", function(d,i){ return colors[i]});
<script src=""></script>

Just a tip: this is not a good approach when you have a big dataset, or when your dataset keeps changing. Instead, use an array of objects in which you can set the color for each object, or create a rule for colouring the bars.