I'm building a pie chart using d3.js, and visualizing a big data set. There are more than 137 items to visualize on the chart. I have just 10 colors using this function.
d3.scale.category10().range()
by exploring other options : https://github.com/mbostock/d3/wiki/Ordinal-Scales
d3.scale.category20().range()
var chart = nv.models.pieChart()
.x(function(d) {
return d.key
})
.y(function(d) {
return d.y
})
.color(d3.scale.category10().range())
.width(width)
.height(height);
How can I generate as many colors as I want using d3?
If you have that many categories, then a pie chart is the wrong chart for the job. Can you summarise (group) the categories?
Also have you considered a starburst chart for the job (again needs grouping).
Stephen Few (data viz expert and author) recommends no more than 9 colours (categories) on a chart.
As you are using a lot of categories it is impossible to use perceptually different colors. The good news is that, in a pie chart, only two colors are next to each one, then all do not need to be different, just those that are adjacent.
What I would do is generate a two different color scales, both using
d3.interpolateHcl()
. HCL and Lab are better color models to generate natural color gradients and are also whatcategory20()
used to generate perceptually different colors.Put the colors you want in the
range([...])
and apply these functions adding some randomness. I'm using the indexi
of the data to alternate between the two color schemes.More on color theory and color models:
And a good HCL color space colorpicker:
UPDATE
The newer versions of d3 provide more colors schemes and interpolators with more sophisticated models. There are some types of schemes and I think the most usefull for this use case are the sequential multi-hue interpolators.
I have developed an interactive widget to explore these scales and interpolators while changing the number of colors. See below.
Note that is also difficult with these schemes to provide several perceptually different colors.
We can use custom colors, for example you can create your own range of colors:
.range(["#fff","#000","#333"]);
. Here is a similar StackOverflow thread: https://stackoverflow.com/a/13013162/1848540I had the same problem, so I wrote a little tool to generate LOTS of perceptually-different colors: category color generator.
This tool produces a list of colors. You can then use that list like:
There is also a generalised version if two lightnesses is not enough.
Here are some pre-generated example colour sets.
I faced the same issue, so using this solution, I expanded it so that it can be used generate 437 colors, I used the color generator mentioned above to generate this colors.
This is not a good solution. Will try to generate the color string automatic in future.
You cant use d3 to get more than 20 colors because its hardcoded list of colors (you can see here the code - https://github.com/mbostock/d3/blob/master/src/scale/category.js)