R - 将图例添加到回归线的 ggplot 图

问题描述

我在 R 中进行了多元线性回归,我想在其中向图形 (ggplot) 添加一个简单的图例。图例应显示具有相应颜色的点和拟合线。到目前为止它工作正常(没有图例):

ggplot() +
  geom_point(aes(x = training_set$R.D.Spend,y = training_set$Profit),col = 'red') +
  geom_line(aes(x = training_set$R.D.Spend,y = predict(regressor,newdata = training_set)),col = 'blue') +
  geom_line(aes(x = training_set$R.D.Spend,y = predict(regressor_sig,col = 'green') +
  ggtitle('Multiple Linear Regression (Training set)') +
  xlab('R.D.Spend [k$]') + 
  ylab('Profit of Venture [k$]')

enter image description here

如何最轻松地在此处添加图例?

我尝试了类似问题的解决方案,但没有成功 (add legend to ggplot2 | Add legend for multiple regression lines from different datasets to ggplot)

所以,我像这样附加了我的原始模型:

ggplot() +
  geom_point(aes(x = training_set$R.D.Spend,col = 'p1') +
  geom_line(aes(x = training_set$R.D.Spend,col = 'p2') +
  geom_line(aes(x = training_set$R.D.Spend,col = 'p3') +
  scale_color_manual(
    name='My lines',values=c('blue','orangered','green')) +
  ggtitle('Multiple Linear Regression (Training set)') +
  xlab('R.D.Spend [k$]') + 
  ylab('Profit of Venture [k$]')

在这里我收到“未知颜色名称:p1”的错误。这有点道理,因为我没有在上面定义 p1。如何让 ggplot 识别出我想要的图例?

解决方法

col 移动到 aes 中,然后您可以使用 scale_color_manual 设置颜色:

library(ggplot2)
set.seed(1)
x <- 1:30
y <- rnorm(30) + x

fit <- lm(y ~ x)
ggplot2::ggplot(data.frame(x,y)) + 
  geom_point(aes(x = x,y = y)) + 
  geom_line(aes(x = x,y = predict(fit),col = "Regression")) + 
  scale_color_manual(name = "My Lines",values = c("blue"))

enter image description here