【问题标题】:regression line on a ggplot is not shown未显示 ggplot 上的回归线
【发布时间】:2020-05-17 12:14:17
【问题描述】:

当我尝试使用 ggplot 时,该图仅以点显示数据,但图中根本没有线。此外,R 中没有错误。数据有两个列,即月份和降雨量。我做了几年的数据集如下:

Month Rainfall
1        0.7
2         0
3         0
.         .
.         .
12         1.2
1         0
2         0.2
.         .
.         .

我的项目的ggplot完整代码如下:

 split = sample.split(dataset$Rainfall, SplitRatio = 0.8)
 training_set = subset(dataset, split == TRUE)
 test_set = subset(dataset, split == FALSE)


 regressor = lm(formula = Rainfall ~ Month,
                data = training_set)

 y_pred = predict(regressor, newdata = test_set)
 y_pred


 library(ggplot2)

 ggplot() + 
   geom_point(aes(x = training_set$Month, y = training_set$Rainfall),
               color = 'red') +
   geom_line(aes(x = training_set$Month, y = predict(regressor, newdata = training_set)),
               color = 'blue') +
   ggtitle('Rainfall (Training set)') +
   xlab('Month') +
   ylab('Rainfall')

 ggplot() + 
   geom_point(aes(x = test_set$Month, y = test_set$Rainfall),
               color = 'red') +
   geom_line(aes(x = training_set$Month, y = predict(regressor, newdata = training_set)),
               color = 'blue') +
   ggtitle('Monthly Rainfall (Test set)') +
   xlab('Month') +
   ylab('Rainfall')

但是,我不能将一条线绘制为简单的线性回归。

【问题讨论】:

  • 您可以使用geom_abline 根据截距和斜率绘制回归线
  • 使用 geom_smooth(method = 'lm') 在 x 和 y 变量之间绘制回归线
  • 你的回归器可能有问题..你能分享一下如何安装的代码吗?还有 dput(test_set) 并将输出粘贴到您的帖子中以共享输出?
  • 还有,training_set 中有什么?

标签: r ggplot2 regression linear-regression


【解决方案1】:

对于 ggplot2,您可以使用 geom_smooth(method="lm") 绘制简单的线性回归线。

你可以参考这个https://github.com/rstudio/cheatsheets/raw/master/data-visualization-2.1.pdf备忘单了解如何使用ggplot2。


您的代码的“固定”版本示例:

library(tidyverse)
test_set %>% ggplot(aes(x = Month, y = Rainfall)) + 
   geom_point() +
   geom_smooth(method="lm", se=FALSE) +
   ggtitle('Monthly Rainfall (Test set)') +
   xlab('Month') +
   ylab('Rainfall')

我用这个作为测试集

test_set <- tribble(
  ~Month, ~Rainfall,
  1,   1,
  2,   2,
  3,   3,
  4,   2,
  5,  .7
)

【讨论】:

  • 感谢您的帮助。很抱歉这么说,我试试你的代码,但它根本不起作用。
  • @R_mad 它应该可以工作我进行了编辑,并提供了示例输出。
  • 对你有用,但我想要我的测试,正如我已经在这篇文章中展示的那样。我认为它没有画线,因为我每个月都有几个值。但在您的示例中,每个月只有一个值。
  • 不,如果每个月有多个值也没关系。
猜你喜欢
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
  • 2019-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多