Search code examples
rlinear-regressionconfidence-interval

To manully plot the CI


How to find the CI of a simple linear regression model? I found different ways to do it but the CIs plotted are different from each other.

Since I am not from a statistics background so I am not sure which one is the correct one. I only have a very basic understanding of CI and linear regression.

The first attempt, I just use the function confint() to plot the straight line.

plot(y~x, data=df)

abline(lm.model)

ci<-confint(lm.model, level=0.95)
abline(ci[1], ci[2])
abline(ci[3], ci[4])

Second attempt from Plotting a 95% confidence interval for a lm object

newx = seq(min(x),max(x),by = 0.05)
conf_interval <- predict(lm.model, newdata=data.frame(x=newx), interval="confidence",
                         level = 0.95)
plot(y~x, data=df, xlab="x", ylab="y", main="Regression")
abline(lm.model, col="lightblue")
lines(newx, conf_interval[,2], col="blue", lty=2)
lines(newx, conf_interval[,3], col="blue", lty=2)

It seems to me that they are all getting the same thing but I am not sure which one is the one I am looking for. Any help is appreciated. Many thanks.


Solution

  • You may try using geom_smooth

    library(dplyr)
    library(ggplot2)
    df %>%
      ggplot(aes(x,y)) +
      geom_point() +
      geom_smooth(method = "lm", level = 0.95)
    

    enter image description here