Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomising qualitative colours for large sets in ggplot

Tags:

If you're mapping qualitatively to colour for a large number of groups, ggplot's automatic colour assignment plots very similar colours adjacently, making it hard to see which refer to which key etc. To illustrate:

require(ggplot2); require(stringr) df = data.frame(x = letters, y = sample(20:100,26), lab=word("apple ball cat dog elephant frog goat hat ice jackal king lion mango nest owl parrot queen rabbit ship tomato umbrella van watch xylophone yatch zebra", 1:26)) p = ggplot(df, aes(x, y, fill=lab)) + geom_bar(stat="identity") p + scale_fill_discrete() 

enter image description here

Its possible to mix up some random colours manually:

cols = rainbow(26, s=.6, v=.9)[sample(1:26,26)] p + scale_fill_manual(values=cols) 

enter image description here

.. resulting in more useful breakup of the rainbow, but this seems clumsy, still leaves some colours clumped together and is generally not ideal. Does ggplot have a native method to achieve something like this (but hopefully better)?

like image 984
geotheory Avatar asked Jan 25 '14 15:01

geotheory


People also ask

How do I specify colors in ggplot2?

To specify colors of the bar in Barplot in ggplot2, we use the scale_fill_manual function of the ggplot2 package. Within this function, we need to specify a color for each of the bars as a vector. We can use colors using names as well as hex codes.

What colors does Ggplot recognize?

By default, ggplot graphs use a black color for lines and points and a gray color for shapes like the rectangles in bar graphs.

Is Ggplot colorblind friendly?

The default colors in ggplot2 can be difficult to distinguish from one another because they have equal luminance. They are also not friendly for colorblind viewers.


1 Answers

Producing a good palette for that many colours is indeed a difficult task. However, there is one solution which may be helpful. Some time ago I forked this repo and found a reference to iWantHue. As far as I can see, the resulting palette is already mixed, so that neighbouring colours look distinguishable.

For instance, for your example I have enter image description here

Just in case, the palette is

"#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7",  "#673770", "#D3D93E", "#38333E", "#508578", "#D7C1B1", "#689030", "#AD6F3B", "#CD9BCD",  "#D14285", "#6DDE88", "#652926", "#7FDCC0", "#C84248", "#8569D5", "#5E738F", "#D1A33D",  "#8A7C64", "#599861" 
like image 135
tonytonov Avatar answered Sep 30 '22 16:09

tonytonov