繁体   English   中英

R - 为回归线添加图例到 ggplot 图

[英]R - Adding legend to ggplot graph for regression lines

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

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, newdata = training_set)),
            col = 'green') +
  ggtitle('Multiple Linear Regression (Training set)') +
  xlab('R.D.Spend [k$]') + 
  ylab('Profit of Venture [k$]')

在此处输入图像描述

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

我尝试了类似问题的解决方案,但没有成功( 将图例添加到 ggplot2 | 将来自不同数据集的多条回归线的图例添加到 ggplot

所以,我像这样附加了我原来的 model :

ggplot() +
  geom_point(aes(x = training_set$R.D.Spend, y = training_set$Profit),
             col = 'p1') +
  geom_line(aes(x = training_set$R.D.Spend, y = predict(regressor, newdata = training_set)),
            col = 'p2') +
  geom_line(aes(x = training_set$R.D.Spend, y = predict(regressor_sig, newdata = training_set)),
            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"))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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