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

帅比萌擦擦* 提交于 2020-05-29 10:07:46

问题


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 times the value and corresponds to the color that has the same index as the value.

This is what I have so far:

d3.select("body").selectAll("div")
            .data(total_data)
            .enter()
            .append("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!


回答1:


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 = d3.select("body")
	.append("svg")
	.attr("width", width)
	.attr("height", height);
	
var bars = svg.selectAll(".myBars")
	.data(values)
	.enter()
	.append("rect");
	
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="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></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.



来源:https://stackoverflow.com/questions/39427222/2-arrays-one-of-values-one-of-colors-make-d3-bar-chart-have-color-at-same-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!