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).
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)
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.
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")
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With