16

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?

konvas
  • 14,126
  • 2
  • 40
  • 46
Meso
  • 1,375
  • 5
  • 17
  • 36

1 Answers1

25

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)

enter image description here

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]))) 
SJ9
  • 477
  • 4
  • 13
konvas
  • 14,126
  • 2
  • 40
  • 46
  • Thanks for you answer. I assume the default must be left align as the first code automatically created left aligned legend. Why did the second script resulted in centred/right aligned output? In which situations do I need to add "theme(legend.text.align = 0)"? – Meso Nov 07 '14 at 08:20
  • 2
    Well the short answer would be whenever the text is not aligned to the left :) I don't know why in this case the alignment is not to the left, which is the default. The reason your script results in right-aligned output has to do with the use of expressions, if you use bquote instead the default left alignment is used -see update – konvas Nov 07 '14 at 10:31