Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign random colors to D3 bar chart?

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

Bar Chart

How do I make the bars to have random colors?

jsFiddle

Code:

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
like image 455
Rahul Desai Avatar asked Feb 17 '14 05:02

Rahul Desai


People also ask

How do you make a bar graph a different color in R?

To set colors for bars in Bar Plot drawn using barplot() function, pass the required color value(s) for col parameter in the function call. col parameter can accept a single value for color, or a vector of color values to set color(s) for bars in the bar plot.

How do I change the color of my bar graph in SAS?

If you have SAS 9.3 or later, you can do this using the SGPLOT procedure. Use LIMITATTRS to change the color of the error bars. You can change the color of the bars themselves using FILLATTRS.


3 Answers

d3 has 4 built in color palettes.

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.

And the official site for d3 colors.

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.

like image 104
Unknown User Avatar answered Oct 20 '22 16:10

Unknown User


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)})
like image 43
Chitrasen Avatar answered Oct 20 '22 16:10

Chitrasen


this is old now, but this is a pretty good approach if you need N number of random colors

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

like image 5
Andy B Avatar answered Oct 20 '22 15:10

Andy B