【发布时间】: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