regrading adding a legend using ggplot2 for different lines

半城伤御伤魂 提交于 2021-02-05 09:23:27

问题


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)

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 ?

Thank you


回答1:


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

Example:

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


来源:https://stackoverflow.com/questions/61730874/regrading-adding-a-legend-using-ggplot2-for-different-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!