Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align legend text in ggplot

Tags:

r

ggplot2

I have difficulty in aligning the legend text to the left.

library(ggplot2)
library(reshape2)
o3<- rnorm(1827, 50, 10)
NO2<- rnorm(1827, 35, 7)
NOx<- rnorm(1827, 45, 10)
pm25<- rnorm(1827, 15, 4)
date<-seq(as.Date('2000-01-01'),as.Date('2004-12-31'),by = 1)
df<-data.frame(date,o3,NO2,NOx,pm25)
meltdf <- melt(df,id="date")

With this code the alignment is automatically to the left

ggplot(meltdf, aes(x = date, y = value, colour =variable)) + geom_smooth() + stat_smooth(method = "gam")

However with the following the alignemt is to the centre.

ggplot(meltdf, aes(x = date, y = value, colour =variable)) + 
      geom_smooth() + stat_smooth(method = "gam") +
      scale_color_discrete(name="Pollutant" ,labels = c(expression(O[3]),
                                expression(NO[2]),
                                expression(NO[x]),
                                expression(PM[2.5]))) 

How could I achieve left alignment with the last script?

like image 542
Meso Avatar asked Nov 06 '14 14:11

Meso


People also ask

How to position legend in ggplot?

In newer versions of ggplot2 , you can use + theme(legend. position='bottom') . See Cookbook for R - Legends for more legends goodness. with results as above, with the difference being that subsequent plots will also default to legend on bottom.


1 Answers

You need to specify legend.text.align in theme():

ggplot(meltdf, aes(x = date, y = value, colour =variable)) + 
geom_smooth() + 
stat_smooth(method = "gam") +
scale_color_discrete(name="Pollutant", 
    labels = c(expression(O[3]),
               expression(NO[2]),
               expression(NO[x]),
               expression(PM[2.5]))) +
theme(legend.text.align = 0)

Alternatively, try using bquote instead of expression, and default left alignment takes place. I don't know why just using expression changes the alignment to the right...

ggplot(meltdf, aes(x = date, y = value, colour =variable)) + 
geom_smooth() + 
stat_smooth(method = "gam") +
scale_color_discrete(name="Pollutant", 
    labels = c(bquote(O[3]),
               bquote(NO[2]),
               bquote(NO[x]),
               bquote(PM[2.5]))) 
like image 171
konvas Avatar answered Oct 15 '22 05:10

konvas