Adding confidence and prediction intervals to graphs in R

Following are two functions you can use to add confidence intervals or prediction intervals to your plots. I’ve wrapped the same basic code up for use with the base plot function in R as well as for the lattice library in R. Note that in both cases you’ll also need to draw the regression line in on your data. First is function for lattice, then the function for base R.

 


panel.ci <- function(x, y, interval='prediction', ...) {	
	require(lattice)
	fit     <- lm(y ~ x, data=data.frame(x=x, y=y))
	newX    <- data.frame(x=jitter(x))
 	fitPred <- predict.lm(fit, newdata=newX, interval=interval, ...)
	panel.lmline(x, y, ..., identifier = "lmline")
	panel.xyplot(newX$x, fitPred[,2], type="a", lty=2, ...)
	panel.xyplot(newX$x, fitPred[,3], type="a", lty=2, ...)
}

 # ---- and here is the lattice code in action ----

require(lattice)
xyplot(y ~ x, data=data.frame(x=1:20, y=1:20+rnorm(20, sd=2)), pch=19,
   panel=function(x,y,...) {
      panel.xyplot(x,y,...)
      panel.ci(x,y,...)})

# Now here is the same thing, but for the base R plotting function. Again, source the code below and you’ll see how it works.

 


plot.add.ci <- function(x, y, interval='prediction', level=0.9, regressionColor='red', ...) {
	xOrder  <- order(x)
	x       <- x[xOrder]  
	y       <- y[xOrder]
        fit     <- lm(y ~ x, data=data.frame(x=x, y=y))
	newX    <- data.frame(x=jitter(x))
	fitPred <- predict.lm(fit, newdata=newX, interval=interval, level=level, ...)
	abline(lm(y ~ x), col=regressionColor)
	lines(newX$x, fitPred[,2], lty=2, ...)
	lines(newX$x, fitPred[,3], lty=2, ...)
}

 # ---- and here it is in action ----

x = 1:20;   
y = 1:20 + rnorm(20, sd=2)
plot(x, y, pch=19)
plot.add.ci(x, y, col='blue')
plot.add.ci(x, y, col='lightblue', level=0.99)