javascript 如何为 D3 条形图分配随机颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21821304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign random colors to D3 bar chart?
提问by Rahul Desai
回答by Unknown User
d3 has 4 built in color palettes.
d3 有 4 个内置调色板。
Here's the link
for the built in color palettes.
这是link
内置调色板的。
This
tutorial is good on using specific colors for specific element.
This
教程非常适合为特定元素使用特定颜色。
Another tutorial
by Jerome Cukier.
tutorial
杰罗姆·库基尔 (Jerome Cukier) 的另一个作品。
And the official site
for d3 colors.
和官方site
为d3颜色。
Fiddle
- Note: In the fiddle I've passed the colors by adding colors in the data.
Fiddle
- 注意:在小提琴中,我通过在数据中添加颜色来传递颜色。
It can even be done by passing the colors from a different variables.
它甚至可以通过传递来自不同变量的颜色来完成。
Hope this helps.
希望这可以帮助。
回答by Chitrasen
colors = d3.scale.category20()
rects = svg.selectAll('rect')
.data(data)
.enter()
.append("rect")
.attr("class","rect")
.....#other attributes
.attr("fill",function(d,i){return colors(i)})
回答by Andy B
this is old now, but this is a pretty good approach if you need N number of random colors
这现在很旧了,但是如果您需要 N 种随机颜色,这是一个很好的方法