简体   繁体   English

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

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

I do a Multiple Linear Regression in R, where I want to add a simple legend to a graph (ggplot).我在 R 中进行了多重线性回归,我想在图中添加一个简单的图例(ggplot)。 The legend should show the points and fitted lines with their corresponding colors.图例应显示点和拟合线及其对应的 colors。 So far it works fine (without legend):到目前为止它工作正常(没有图例):

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

在此处输入图像描述

How can I add a legend here most easily?如何最轻松地在此处添加图例?

I tried the solutions from similar question, but did not succeed ( add legend to ggplot2 | Add legend for multiple regression lines from different datasets to ggplot )我尝试了类似问题的解决方案,但没有成功( 将图例添加到 ggplot2 | 将来自不同数据集的多条回归线的图例添加到 ggplot

So, I appended my original model like this:所以,我像这样附加了我原来的 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$]')

But here I am getting the error of "Unknown colour name: p1".但在这里我收到“未知颜色名称:p1”的错误。 which makes somewhat sense, as I do not define p1 above.这有点道理,因为我没有在上面定义 p1 。 How can I make the ggplot recognise my intended legend?如何让 ggplot 识别我想要的图例?

Move col into the aes and then you can set the color using scale_color_manual :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