Reverse scale_fill_brewer

3,146 views
Skip to first unread message

Tyler Rinker

unread,
Apr 19, 2012, 3:10:45 AM4/19/12
to ggplot

I'd like to reverse the assignment of scale_fill_brewer.  So for instance in the plot below Fair is currently dark red and ideal is dark blue.  I'd like to reverse the mapping to Fair is dark blue and ideal is dark red.

#sample code

ggplot(diamonds, aes(x=price, fill=cut)) +

    geom_histogram(position="dodge", binwidth=1000) +

    scale_fill_brewer(palette="RdYlBu")

Running ggplot2 0.9, win 7, R 2.15
Thank you in advance for your help.
Tyler Rinker

Jean-Olivier Irisson

unread,
Apr 19, 2012, 3:30:23 AM4/19/12
to Tyler Rinker, ggplot
On 2012-Apr-19, at 09:10 , Tyler Rinker wrote:
>
> ggplot(diamonds, aes(x=price, fill=cut)) +
>
> geom_histogram(position="dodge", binwidth=1000) +
>
> scale_fill_brewer(palette="RdYlBu")

Reverse the order in the data

diamonds$cut = factor(diamonds$cut, levels=rev(levels(diamonds$cut)))


ggplot(diamonds, aes(x=price, fill=cut)) +
geom_histogram(position="dodge", binwidth=1000) +
scale_fill_brewer(palette="RdYlBu")

Or reverse the palette mapping

library("ggplot2")
library("RColorBrewer")
colours= brewer.pal(name="RdYlBu", n=nlevels(diamonds$cut))
names(colours)= rev(levels(diamonds$cut))


ggplot(diamonds, aes(x=price, fill=cut)) +
geom_histogram(position="dodge", binwidth=1000) +

scale_fill_manual(values=colours)

Jean-Olivier Irisson
---
Observatoire Océanologique
Station Zoologique, B.P. 28, Chemin du Lazaret
06230 Villefranche-sur-Mer
Tel: +33 04 93 76 38 04
Mob: +33 06 21 05 19 90
http://jo.irisson.com/

Tyler Rinker

unread,
Apr 19, 2012, 9:55:13 AM4/19/12
to iri...@normalesup.org, ggplot

Jean-Olivier Irisson,
Both methods worked very well.  I learned a little bit more about how RColorBrewer operates (particularly from your second example).  I went with he second example because it messed with less things (such as legend order etc.).  Thank you for the help.
Tyler Rinker

----------------------------------------
> Subject: Re: Reverse scale_fill_brewer
> From: iri...@normalesup.org
> Date: Thu, 19 Apr 2012 09:30:23 +0200
> CC: ggp...@googlegroups.com
> To: tyler_...@hotmail.com

Reply all
Reply to author
Forward
0 new messages