首页 > 解决方案 > 使用 ggplot2 为不同的行重新添加图例

问题描述

我想添加一个图例,它会告诉使用ggplot2. 我的代码如下:

require(lme4)
require(ggplot2)
m1 <- lmer(Reaction ~ 1+I(Days) + (1+ Days| Subject) , data = sleepstudy)

pred1new1=predict(m1,re.form=NA)

为了添加一个图例,我试过了scale_colour_manual,但没有用。

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'))

在此处输入图像描述

任何人都可以提出任何解决此问题的建议吗?

谢谢

标签: rggplot2legend

解决方案


将颜色参数放入aes并为其指定要在图例中显示的名称,然后选择标题和颜色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'))

推荐阅读