Regression line on a ggplot is not shown

1k views Asked by At

When I try to use ggplot, the plot just shows data in dots, but there is no line at all in the plot. Also, there is no error in R. Data has two columns, Month and Rainfall.

I made dataset as following for several years:

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

The full code for ggplot of my project is as follow :

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

But, I cannot plot a line as simple linear regression.

1

There are 1 answers

4
Arik On

For ggplot2 you can use geom_smooth(method="lm") to plot a simple linear regression line.

You may refer to this https://github.com/rstudio/cheatsheets/raw/master/data-visualization-2.1.pdf cheat-sheet for how to use ggplot2.


Example of a 'fixed' version of your code:

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

I used this as the test_set

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

Example of code above