如何在R

时间:2016-03-29 05:37:06

标签: r ggplot2 spline

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

我有两个样条:红色和蓝色。我如何为他们添加传奇?

1 个答案:

答案 0 :(得分:11)

将颜色放在aes()中并添加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"))

enter image description here