r - ggplot2: how to get robust confidence interval for predictions in geom_smooth? -
consider simple example
dataframe <- data_frame(x = c(1,2,3,4,5,6), y = c(12,24,24,34,12,15)) > dataframe # tibble: 6 x 2 x y <dbl> <dbl> 1 1 12 2 2 24 3 3 24 4 4 34 5 5 12 6 6 15 dataframe %>% ggplot(., aes(x = x, y = y)) + geom_point() + geom_smooth(method = 'lm', formula = y~x)
here standard errors computed default option. however, use robust variance-covariance matrix available in package sandwich
, lmtest
that is, using vcovhc(mymodel, "hc3")
is there way in simple way using geom_smooth()
function?
i new whole robust se thing, able generate following:
zz = ' x y 1 1 12 2 2 24 3 3 24 4 4 34 5 5 12 6 6 15 ' df <- read.table(text = zz, header = true) df library(sandwich) library(lmtest) lm.model<-lm(y ~ x, data = df) coef(lm.model) se = sqrt(diag(vcovhc(lm.model, type = "hc3"))) fit = predict(lm.model) predframe <- with(df,data.frame(x, y = fit, lwr = fit - 1.96 * se, upr = fit + 1.96 * se)) library(ggplot2) ggplot(df, aes(x = x, y = y))+ geom_point()+ geom_line(data = predframe)+ geom_ribbon(data = predframe, aes(ymin = lwr,ymax = upr), alpha = 0.3)
Comments
Post a Comment