在ggplot中对齐图例文本

Mes*_*eso 8 r ggplot2

我很难将图例文本对齐到左侧.

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")
Run Code Online (Sandbox Code Playgroud)

使用此代码,对齐自动向左

ggplot(meltdf, aes(x = date, y = value, colour =variable)) + geom_smooth() + stat_smooth(method = "gam")
Run Code Online (Sandbox Code Playgroud)

然而,以下是alignemt到中心.

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]))) 
Run Code Online (Sandbox Code Playgroud)

我怎么能用最后一个脚本实现左对齐?

kon*_*vas 10

您需要指定legend.text.aligntheme():

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)
Run Code Online (Sandbox Code Playgroud)

或者,尝试使用bquote而不是expression,并且默认左对齐发生.我不知道为什么只是使用expression更改右对齐...

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]))) 
Run Code Online (Sandbox Code Playgroud)

  • 好吧,简短的答案是每当文本未向左对齐时 :) 我不知道为什么在这种情况下对齐不向左,这是默认设置。您的脚本导致右对齐输出的原因与表达式的使用有关,如果您使用 bquote 而不是使用默认的左对齐 - 请参阅更新 (2认同)