简体   繁体   中英

How to add legend to geom_smooth in ggplot in R

Have a problem of adding legend to different smooth in ggplot.

    library(splines)
    library(ggplot2)
    temp <- data.frame(x = rnorm(200, 20, 15), y = rnorm(200, 30, 8))

    ggplot(data = temp, aes(x, y)) + geom_point() + 
      geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), col='blue') + 
      geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), col='red')

I have two splines: red and blue. How I can add a legend for them?

Put the colour in aes() and add scale_colour_manual() :

ggplot(data = temp, aes(x, y)) + geom_point() + 
  geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), aes(colour="A")) + 
  geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), aes(colour="B")) +
  scale_colour_manual(name="legend", values=c("blue", "red"))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM