简体   繁体   中英

How do I add confidence intervals to glm model in ggplot?

Here is an example of what my data looks like:

DATA <- data.frame(
TotalAbund = sample(1:10),
TotalHab = sample(0:1),
TotalInv = sample(c("yes", "no"), 20, replace = TRUE)
)
DATA$TotalHab<-as.factor(DATA$TotalHab)
DATA

Here is my model:

MOD.1<-glm(TotalAbund~TotalInv+TotalHab, family=quasipoisson, data=DATA)

Here is my plot:

NEWDATA <- with(DATA,
               expand.grid(TotalInv=unique(TotalInv),
                       TotalHab=unique(TotalHab)))

pred <- predict(MOD.1,newdata= NEWDATA,se.fit=TRUE)
gg1 <- ggplot(NEWDATA, aes(x=factor(TotalHab), y=TotalAbund,colour=TotalInv))

I get the following error...

Error in eval(expr, envir, enclos) : object 'TotalAbund' not found

...when trying to run the last line of code:

gg1 + geom_point(data=pframe,size=8,shape=17,alpha=0.7,
             position=position_dodge(width=0.75))

Can anyone help? Also how do I add 95% confidence intervals to my points? Thanks.

You will need to calculate the 95% confidence intervals yourself. You were on the right track using predict and asking for the se.fit . We will first ask for the predictions on the link scale, calculate 95% confidence intervals, and then transform them to the real scale for plotting. Here is a convenience function to calculate your CI's for the log link (which you used in the model).

# get your prediction
pred <- predict(MOD.1,newdata= NEWDATA,se.fit=TRUE,
            type = "link")

# CI function
make_ci <- function(pred, data){

# fit, lower, and upper CI
fit <- pred$fit
lower <- fit - 1.96*pred$se.fit
upper <- fit + 1.96*pred$se.fit

return(data.frame(exp(fit), exp(lower), exp(upper), data))
}

my_pred <- make_ci(pred, NEWDATA)

# to be used in geom_errorbar
limits <- aes(x = factor(TotalHab), ymax = my_pred$exp.upper., ymin = my_pred$exp.lower.,
                     group = TotalInv)

Then we plot it out, I will leave the final tweaking to you to make the figure out how you want it to.

ggplot(my_pred, aes(x = factor(TotalHab), y = exp.fit., color = TotalInv))+
geom_errorbar(limits, position = position_dodge(width = 0.75),
            color = "black")+
geom_point(size = 8, position = position_dodge(width = 0.75), shape = 16)+
ylim(c(0,15))+
geom_point(data = DATA, aes(x = factor(TotalHab), y = TotalAbund, colour = TotalInv),
         size = 8, shape = 17, alpha = 0.7,
         position = position_dodge(width = 0.75))

情节

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