Reputation: 1979
I would like to get the upper and lower limits of the confidence interval for each observation in loess function to replicate what ggplot
does in the geom_smooth()
library(ggplot2)
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(method = 'loess')
I know I can get the upper and lower bounds from linear models, but this is not available for loess:
lm_mod <- lm(hp ~ mpg, mtcars)
predict(lm_mod, mtcars, interval="confidence", level=0.95)
loess_mod <- loess(hp ~ mpg, mtcars)
predict(loess_mod, mtcars, interval="confidence", level=0.95)
Upvotes: 5
Views: 7832
Reputation: 1979
Figured it out! The confidence intervals can be calculated from the standard errors which can be added prediction object using the se = TRUE
argument. 1.96 standard deviations equates to a 95% confidence interval (with a normal distribution and hence assuming normality in the errors).
loess_mod <- loess(hp ~ mpg, mtcars)
pred <- predict(loess_mod, mtcars, se=TRUE)
mtcars1$lwl <- pred$fit-1.96*pred$se.fit
mtcars1$upl <- pred$fit+1.96*pred$se.fit
library(ggplot2)
ggplot(mtcars1, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(method = 'loess') +
geom_line(aes(y = lwl), color = "red") +
geom_line(aes(y = upl), color = "red")
Hope this helps someone else.
Upvotes: 15