微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。