Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Plot discrete factors with a set of similar colours

Tags:

plot

r

ggplot2

I'm trying to come up with a consistent way of representing each factor in my dataset when plotting them. So, for example, I could have the levels of "Part of Speech" represented by different shades of blue every time I'm graphing something involving part of speech:

eg.dat <- data.frame(rt=c(530, 540, 555), 
                     part.of.speech=c("Verb", "Noun", "Both")
                     )

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
  geom_bar(stat="identity", colour="black") +
  scale_fill_manual(values=c("cyan", "blue", "darkblue")) 

Specifying colours manually

Coming up with fancy colour names like this for every factor is difficult, however, so I've been looking for more automatic solutions. One fairly hackish workaround is to use alpha:

ggplot(eg.dat, aes(part.of.speech, rt, alpha=part.of.speech)) +
  geom_bar(stat="identity", colour="black", fill="blue") +
  scale_alpha_discrete(range=c(0.4, 1))

Using alpha

But I've been wondering whether there's any easier way to select a short range of similar colours like this. The scale_colour_gradient type functions in ggplot2 don't work with discrete factors like these, and it doesn't seem particularly easy to get custom colours out of rainbow or heat.colors. The ideal function would be something like: shades(n, central_colour="blue"), returning n colour values. Any suggestions for the best way to achieve this?

like image 604
Marius Avatar asked Dec 27 '22 20:12

Marius


1 Answers

scale_fill_discrete or scale_fill_hue will do this. You can define h, c and l (hue, chroma and luminance). See ?hcl for more detail

eg.

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
     geom_bar(stat="identity", colour="black") +
     scale_fill_discrete( h =c(220,260))

enter image description here

scale_fill_hue will give the same results (in this case).

You could also use scale_fill_brewer which uses the RColorBrewer package and gives access to the colorbrewer palettes

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
     geom_bar(stat="identity", colour="black") +
     scale_fill_brewer(palette = 'Blues')

enter image description here

like image 118
mnel Avatar answered Jan 13 '23 13:01

mnel