使用ggplot2为不同的行添加图例 [英] regrading adding a legend using ggplot2 for different lines
本文介绍了使用ggplot2为不同的行添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想添加一个图例,该图例将使用 ggplot2
分辨出哪种颜色代表哪条线.我的代码如下:
I want to add a legend that will tell which color represents which line using ggplot2
.
My code is as follows :
require(lme4)
require(ggplot2)
m1 <- lmer(Reaction ~ 1+I(Days) + (1+ Days| Subject) , data = sleepstudy)
pred1new1=predict(m1,re.form=NA)
要添加图例,我尝试了 scale_colour_manual
,但没有成功.
To add a legend, i tried scale_colour_manual
, but it didnt worked.
p21 <- ggplot(data = sleepstudy, aes(x = Days, y = Reaction))
p21+ geom_point() + geom_smooth(col="blue")+ geom_line(aes(y=pred1new1,group = Subject) ,col="red", lwd = 0.5)+
scale_colour_manual(name = 'the colour',
values =c('blue'='blue','red'='red'), labels = c('smooth','pred'))
任何人都可以提出任何解决方案的建议吗?
Can anyone suggest anything to fix this ?
谢谢
推荐答案
将color参数放入 aes
中,并为其指定要在图例中显示的名称,然后选择标题和颜色在 scale_color_manual
Put the color parameter in aes
and give it the name you want to show in the the legend and then choose the title and colors in scale_color_manual
示例:
library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(aes(color='Smooth 1')) +
geom_smooth(aes(y = (hwy -1), color='Smooth 2')) +
scale_color_manual('Legend Title', values=c('Smooth 1'='blue', 'Smooth 2'='red'))
这篇关于使用ggplot2为不同的行添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文