rplotregressionlineabline

Plotting adjusted regression with least squares


I have a regression model fitted with least squares.

library(TSA)
data(hours)
lmhr2 <- lm(hours ~ time(hours)+ I(time(hours)^2), data =hours) 
summary(lmhr2)

plot(hours)
abline(lmhr2)

When I run abline to the plot, I get this error:

In abline(lmhr2) : only using the first two of 3 regression coefficients


Solution

  • You can plot your model using ggplot2::geom_smooth():

    library(TSA)
    library(ggplot2)
    data(hours)
    
    data.frame(time = time(hours), hours = hours) |>  
      ggplot(aes(time, hours)) +
      geom_smooth(method = lm, formula = y ~ x + I(x^2))