如何给D3条形图分配随机颜色?

时间:2022-11-19 13:20:31

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

我正在做一个D3条形图,根据以下的模型:

如何给D3条形图分配随机颜色?

How do I make the bars to have random colors?

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

jsFiddle

jsFiddle

Code:

代码:

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

3 个解决方案

#1


18  

d3 has 4 built in color palettes.

d3有4个彩色调色板。

Here's the link for the built in color palettes.

这是建立在彩色调色板上的链接。

This tutorial is good on using specific colors for specific element.

本教程适用于特定元素的特定颜色。

Another tutorial by Jerome Cukier.

Jerome Cukier的另一篇教程。

And the official site for d3 colors.

以及d3颜色的官方网站。

Fiddle - Note: In the fiddle I've passed the colors by adding colors in the data.

小提琴:在小提琴中,我通过在数据中添加颜色来传递颜色。

It can even be done by passing the colors from a different variables.

它甚至可以通过从不同的变量中传递颜色来完成。

Hope this helps.

希望这个有帮助。

#2


6  

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)})

#3


5  

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

#1


18  

d3 has 4 built in color palettes.

d3有4个彩色调色板。

Here's the link for the built in color palettes.

这是建立在彩色调色板上的链接。

This tutorial is good on using specific colors for specific element.

本教程适用于特定元素的特定颜色。

Another tutorial by Jerome Cukier.

Jerome Cukier的另一篇教程。

And the official site for d3 colors.

以及d3颜色的官方网站。

Fiddle - Note: In the fiddle I've passed the colors by adding colors in the data.

小提琴:在小提琴中,我通过在数据中添加颜色来传递颜色。

It can even be done by passing the colors from a different variables.

它甚至可以通过从不同的变量中传递颜色来完成。

Hope this helps.

希望这个有帮助。

#2


6  

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)})

#3


5  

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