我很难将图例文字对齐到左边。
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")
使用此代码,对齐将自动显示在左侧
ggplot(meltdf, aes(x = date, y = value, colour =variable)) + geom_smooth() + stat_smooth(method = "gam")
然而,以下是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])))
如何使用最后一个脚本实现左对齐?
答案 0 :(得分:10)
您需要在legend.text.align
中指定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)
或者,尝试使用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])))