How to assign random colors to D3 bar chart?

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

How do I make the bars to have random colors?



.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")


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.

colors = d3.scale.category20()

rects = svg.selectAll('rect')
                .....#other attributes
                .attr("fill",function(d,i){return colors(i)})

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

Need Your Help

Spring methods being called twice

spring jsf servlets primefaces

I have a Spring, PrimeFaces JSF application configured to load an application through a class that implements WebApplicationInitializer rather than web.xml (I do still have a bare web.xml) though. ...

How to create a scrollable Java Box?

java swing scroll box scrollpane

I have a Box (verticalBox) in a panel, with checkboxes inside, and i would to do it scrollable.