2017-06-24 52 views
0

我想獲得在黃土功能各觀測置信區間的上限和下限複製什麼ggplot確實在geom_smooth()置信區間/帶的黃土複製geom_smooth

library(ggplot2) 
ggplot(mtcars, aes(x = mpg, y = hp)) + 
    geom_point() + 
    geom_smooth(method = 'loess') 

Points and Loess Function for ggplot

我知道我可以從線性模型的上限和下限,但這不適用於黃土:

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) 

回答

1

想通了!置信區間可以通過使用參數se = TRUE可以添加預測對象的標準誤差來計算。 1.96標準差等於95%置信區間(正態分佈,因此假設誤差正常)。

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

enter image description here

希望這可以幫助其他人。