在ggplot中对齐图例文本 [英] Align legend text in ggplot
本文介绍了在ggplot中对齐图例文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难将图例文本向左对齐.
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?
推荐答案
您需要在theme()
中指定legend.text.align
:
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
可以将对齐方式更改为右侧...
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])))
这篇关于在ggplot中对齐图例文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文