[当我尝试使用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')
但是,我不能将线画为简单的线性回归。
对于ggplot2,您可以使用geom_smooth(method =“ lm”)绘制一条简单的线性回归线。
您可以参考此https://github.com/rstudio/cheatsheets/raw/master/data-visualization-2.1.pdf速查表以了解如何使用ggplot2。
代码的'固定'版本示例:
library(tidyverse)
test_set %>% ggplot() +
geom_point(aes(x = Month, y = Rainfall)) +
geom_smooth(method="lm", se=FALSE) +
ggtitle('Monthly Rainfall (Test set)') +
xlab('Month') +
ylab('Rainfall')