简体   繁体   中英

Confidence Interval/Band for a Loess to Replicate geom_smooth

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

ggplot的点和黄土函数

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM