2个数组之一值的颜色之一使D3条形图在相同的值索引处具有颜色 [英] 2 arrays one of values one of colors make D3 bar chart have color at same index of value
问题描述
我有2个数组:
values = [1,2,3,4,5,4,7,2,9,10];
colors = ['red','red','blue','blue','green','green','orange','orange','pink','pink'];
我正在尝试构建一个D3条形图,其中每个条形的高度都是该值的10倍,并且与具有与该值相同的索引的颜色相对应.
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)];
})
但是,说我们有一个重复的值,那么它将返回错误的颜色.我还尝试从2个数组创建一个JSON,然后将其作为数据传递,但是我遇到了麻烦.做到上述最佳方法是什么?谢谢!
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
您只需要使用每个条形的索引访问数组colors
:
You just need to access the array colors
using the index of each bar:
.attr("fill", function(d,i){ return colors[i]});
这是一个可行的示例(为简单起见,使用宽度为值的10倍,而不是高度的10倍):
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.
这篇关于2个数组之一值的颜色之一使D3条形图在相同的值索引处具有颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!