Create prediction interval in ggplot (different data for points and ribbon geoms)

Viewed 7818

I am trying to create a prediction interval plot using ggplot2(). I hope to only plot points in the original data frame that are outside the prediction interval, and to plot the prediction interval ribbon for a sequence of x values created in another data frame that covers the minimum and maximum x values used in the original data frame. Below is a mwe to demonstrate the details:

library(ggplot2) 

dat <- data.frame(qsec=mtcars$qsec, wt=mtcars$wt)
m <- lm(wt ~ qsec, data = dat) 
mpi <- cbind(dat, predict(m, interval = "prediction"))
# Keep only points that are outside the prediction interval
plotPoints <- mpi[which(!(mpi$wt > mpi$lwr & mpi$wt < mpi$upr)),]

# Create prediction interval data frame with upper and lower lines corresponding to sequence covering minimum and maximum of x values in original dataset
newx <- seq(min(mpi$qsec), max(mpi$qsec), by=0.05)
pred_interval <- predict(m, newdata=data.frame(qsec=newx), interval="prediction", level = 0.95)
pred_interval <- as.data.frame(pred_interval)

# Below are three different attempts to plot the prediction upper and lower lines as ribbons and the points outside the prediction interval as points. Each attempt gives an error which is also commented.

# Error: Object 'qsec' not found
ggplot(data=plotPoints, aes(x = qsec, y = wt)) + geom_point() + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 

# Error: Object 'wt' not found
ggplot(data=plotPoints, aes(x = qsec)) + geom_point(y = wt) + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 

# Error: geom_ribbon requires the following missing aesthetics: x
ggplot(data=plotPoints) + geom_point(aes(x = qsec, y=wt)) + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 

Any advice on how to achieve this type of plot would be much appreciated.

1 Answers
Related