[R] Question on Plotting

Marc Schwartz mschwartz at medanalytics.com
Sun Mar 30 17:12:23 CEST 2003


>-----Original Message-----
>From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] 
>On Behalf Of Jeremy
>Sent: Sunday, March 30, 2003 2:13 AM
>To: R-help at stat.math.ethz.ch
>Subject: [R] Question on Plotting
>
>
>I am looking to plot confidence and prediction interval bands for a
specfic set of data.  
>What R commands would i use to plot this data?

There is an example in ?predict.lm (which you should read), but it
does not include the scatterplot. So if you want the data points
themselves included in your graph, you can use something like the
following:

# Generate x and y
x <- rnorm(50)
y <- x + rnorm(50)

# Create model
mod <- lm(y ~ x)

# Generate new dataframe containing prediction data
# of 50 points over the range of x values
# This does two things:
# 1. It limits the prediction based values of x to 
# the range of known data
# 2. It keeps the values of x in numeric sequence for
# matlines()
# Be sure that the new data frame colnames are the same
# as your model terms
new <- data.frame(x = seq(min(x), max(x),
                      by = (max(x) - min(x)) / 49))

# Now create matrix of fitted values and upper and lower limits
# for prediction bands and confidence bands
pred.lim <- predict(mod, newdata = new, interval = "prediction")
conf.lim <- predict(mod, newdata = new, interval = "confidence")

# Generate plot, setting y axis to include range of 
# prediction values
plot(x, y, xlab = "x", ylab = "y", col = "black", bg = "red", 
     pch = 21, las = 1, cex = 0.9, ylim = range(y, pred.lim, na.rm =
TRUE))

# Use matlines() to draw fitted line and pred/conf bands
matlines(new$x, pred.lim, lty = c(1, 4, 4), 
         lwd = c(2, 1, 1), col = c("black", "red", "red"))

matlines(new$x, conf.lim, lty = c(1, 3, 3), 
         lwd = c(2, 1, 1), col = c("black", "darkgreen", "darkgreen"))



Hope that helps,

Marc Schwartz



More information about the R-help mailing list