[R] ggplot incorrect legend

John Kane jrkrideau at inbox.com
Sat Jun 9 15:42:29 CEST 2012


library(ggplot2)
p  <-  ggplot(data=tempTable, aes(x=Bands8, y=AvailableMWNewFormat, fill=as.factor(FuelTypeNum))) +
        geom_bar(position="stack", stat="identity")+
        coord_flip() + scale_fill_discrete("test") + 
       scale_fill_manual("FuelTypeNum",values= c("1" = "blue", "2" = "red", "4" ="green", "5"="orange"),
        breaks=c("1", "2", "4", "5"),
        labels=c("biomass", "coal", "gas", "hydro")) 

Hydro?  Canadian, eh?

By the way, I just stole the solution from the Cookbook for R http://wiki.stdout.org/rcookbook/Graphs/Legends%20%28ggplot2%29/

Here is a slightly different approach using the RColorBrewer package.  The colours are a bit less garish than the ones I randomly picked.

library(ggplot2)
p  <-  ggplot(data=tempTable, aes(x=Bands8, y=AvailableMWNewFormat, fill=as.factor(FuelTypeNum))) +
        geom_bar(position="stack", stat="identity")+
        coord_flip() +
       scale_fill_brewer(palette="Set1", name="Energy\nSources",
        breaks=c("1", "2", "4", "5"),
         labels=c("biomass", "coal", "gas", "hydro")) 
p

John Kane
Kingston ON Canada

> -----Original Message-----
> From: james at crosb.ie
> Sent: Fri, 8 Jun 2012 10:29:11 -0700 (PDT)
> To: r-help at r-project.org
> Subject: Re: [R] ggplot incorrect legend
> 
> Thank you, that was very helpful.
> 
> Would it be possible to rename the legend values as well. Example 1 as
> Biomass, 2 as coal, 4 as gas, 5 as hydro?
> 
> ggplot(data=tempTable, aes(x=Bands8, y=AvailableMWNewFormat,
> fill=as.factor(FuelTypeNum))) +
>   geom_bar(position="stack", stat="identity")+
>   guides(fill = guide_legend(title = "Fuel Type", title.position =
> "top"))+
>   xlab( "Price Bands")+
>   ylab("Available MW")

____________________________________________________________
FREE ONLINE PHOTOSHARING - Share your photos online with your friends and family!
Visit http://www.inbox.com/photosharing to find out more!



More information about the R-help mailing list