[R] plotting confidence intervals

Marc Schwartz marc_schwartz at me.com
Tue Jul 14 18:43:55 CEST 2009


On Jul 14, 2009, at 10:40 AM, Erin Hodgess wrote:

> Hi R People:
>
> If I have a fitted values from a model, how do I plot the
> (1-alpha)100% confidence intervals along with the fitted values,
> please?
>
> Also, if the intervals are "shaded" gray, that would be nice too,  
> please?
>
> I check confint, but that doesn't seem to do what I want.
>
> Thanks in advance,
> Sincerely,
> Erin



Erin,

confint() will get you the CI's for the model coefficients.

Presuming that you are referring to a lm() model, take a look at ? 
predict.lm and note the 'interval' argument and the examples therein.

If you are looking for CIs for the fitted line ('narrow'), you will  
want to use 'interval = "confidence"'.

If you are looking for CI's for future observations ('wide'), you will  
want to use 'interval = "prediction".


For shading, using the example in ?predict.lm and presuming that you  
want "confidence":

x <- rnorm(15)
y <- x + rnorm(15)
new <- data.frame(x = seq(-3, 3, 0.5))

pred.w.clim <- predict(lm(y ~ x), new, interval="confidence")


# Just create a blank plot region with axes first. We'll add to this
plot(range(new$x), range(pred.w.clim), type = "n", ann = FALSE)


# For convenience
CI.U <- pred.w.clim[, "upr"]
CI.L <- pred.w.clim[, "lwr"]

# Create a 'loop' around the x values. Add values to 'close' the loop
X.Vec <- c(new$x, tail(new$x, 1), rev(new$x), new$x[1])

# Same for y values
Y.Vec <- c(CI.L, tail(CI.U, 1), rev(CI.U), CI.L[1])

# Use polygon() to create the enclosed shading area
# We are 'tracing' around the perimeter as created above
polygon(X.Vec, Y.Vec, col = "grey", border = NA)


# Use matlines() to plot the fitted line and CI's
# Add after the polygon above so the lines are visible
matlines(new$x, pred.w.clim, lty = c(1, 2, 2), type = "l", col =  
c("black", "red", "red"))


See ?polygon and ?matlines


HTH,

Marc Schwartz




More information about the R-help mailing list