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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:45:50  来源:igfitidea点击:

How to assign random colors to D3 bar chart?

javascriptd3.js

提问by Rahul Desai

I am working on a D3 bar chart as per the mock-up below:

我正在按照下面的模型制作 D3 条形图:

Bar Chart

条形图

How do I make the bars to have random colors?

如何使条形具有随机颜色?

jsFiddle

js小提琴

Code:

代码:

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

回答by Unknown User

d3 has 4 built in color palettes.

d3 有 4 个内置调色板。

Here's the linkfor the built in color palettes.

这是link内置调色板的。

Thistutorial is good on using specific colors for specific element.

This教程非常适合为特定元素使用特定颜色。

Another tutorialby Jerome Cukier.

tutorial杰罗姆·库基尔 (Jerome Cukier) 的另一个作品。

And the official sitefor 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 种随机颜色,这是一个很好的方法

http://bl.ocks.org/jdarling/06019d16cb5fd6795edf

http://bl.ocks.org/jdarling/06019d16cb5fd6795edf