stat_smooth and prediction interval

4,253 views
Skip to first unread message

neuwirthe

unread,
Feb 11, 2015, 6:09:25 PM2/11/15
to ggp...@googlegroups.com
c <- ggplot(mtcars, aes(qsec, wt))+geom_point()
c + stat_smooth(method="lm")

displays the confidence interval for the conditional mean.
Is there a way of getting the prediction interval instead.
The predict function in base R allows to do this.

Dennis Murphy

unread,
Feb 11, 2015, 7:34:35 PM2/11/15
to neuwirthe, ggplot2
Hi:

ggplot2 does not support prediction intervals natively so you have to
roll your own and add them to the plot manually.

# Fit a linear model
m <- lm(wt ~ qsec, data = mtcars)
# cbind the predictions to mtcars
mpi <- cbind(mtcars, predict(m, interval = "prediction"))

library(ggplot2)
ggplot(mpi, aes(x = qsec)) +
geom_ribbon(aes(ymin = lwr, ymax = upr),
fill = "blue", alpha = 0.2) +
geom_point(aes(y = wt)) +
geom_line(aes(y = fit), colour = "blue", size = 1)


Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages