Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 reverse order of scale_brewer

Tags:

r

ggplot2

Seemingly a very simple thing to do but it took me >30min without finding answer.

How do I reverse the order of colors? By looking at documentation for scale_brewer, i figured it can be formatter= argument being suspicious. I passed 'rev' and then rev, but they have no effect (no error message, just ignored).

like image 507
yosukesabai Avatar asked Jan 05 '12 22:01

yosukesabai


4 Answers

The CRAN version of ggplot2 now allows users to specify direction=-1 in scale_brewer to reverse the colors. The following produces the same plot as the accepted answer.

ggplot(mtcars,aes(x = mpg, y = disp)) + 
  geom_point(aes(colour = factor(cyl))) + 
  scale_colour_brewer(palette="BuPu", direction=-1)
like image 176
pbaylis Avatar answered Nov 18 '22 03:11

pbaylis


I think you probably want to select the colors using brewer.pal directly and then use scale_colour_manual:

library(ggplot2)
library(RColorBrewer)

ggplot(mtcars,aes(x = mpg, y = disp)) + 
    geom_point(aes(colour = factor(cyl))) + 
    scale_colour_manual(values = rev(brewer.pal(3, "BuPu")))

Then you can rev the order of the colors there.

As of version 2.0,0 of ggplot there is now a more direct way to do this, see the answer by @pbaylis below.

like image 70
joran Avatar answered Nov 18 '22 02:11

joran


This will not help with the OP's problem - I know. For discrete scales like scale_..._brewer(), doing scale_..._manual(values = rev(colorsYouHad)) is the right answer.

Nevertheless, for continuous scales, you can simply pass:

scale_..._...(..., trans = "reverse")

e.g., for the continuous equivalent of scale_..._brewer():

scale_..._distiller("My Scale", palette = "Spectral", trans = "reverse")

like image 30
Antoine Lizée Avatar answered Nov 18 '22 02:11

Antoine Lizée


If you don't want to muck around directly with RColorBrewer (a lovely package), you can reverse the levels of the factor in the original data.frame, and then plot it:

dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

# Reverse the levels of the factor associated with color, here 'clarity'
# (Might be safer to assign this to a new column named, e.g., 'clarity2')
levels(dsamp$clarity) <- rev(levels(dsamp$clarity))

d <- qplot(carat, price, data = dsamp, colour = clarity)
d + scale_colour_brewer(breaks = levels(dsamp$clarity))

And if you want to print the key in the same order as before the reversal, just do this:

d + scale_colour_brewer(breaks = rev(levels(dsamp$clarity)))
like image 11
Josh O'Brien Avatar answered Nov 18 '22 02:11

Josh O'Brien