# How to graphically compare predicted and actual values from multivariate regression in R?

I'm trying to write a function to graphically display predicted vs. actual relationships in a linear regression. What I have so far works well for linear models, but I'd like to extend it in a few ways.

1. Handle glm models
2. Deal with NAs in the predicted values

Does what I have so far seem like a good solution, or is there an existing package somewhere that's already implemented this?

DF <- as.data.frame(na.exclude(airquality))
DF$Month <- as.factor(DF$Month)
DF$Day <- as.factor(DF$Day)

my_model <- lm(Ozone~Solar.R+Wind+Temp+Month+Day,DF)

PvA<- function(model,varlist=NULL,smooth=.5) { #Plot predicted vs actual for a model

indvars <- attr(terms(model),"term.labels")

if (is.null(varlist)) {
varlist <- indvars
}

Y <- as.character(as.list(attr(terms(model),"variables"))[2])
P.Y <- paste('P',Y,sep='.')

DF <- as.data.frame(get(as.character(model$call$data)))
DF[,P.Y] <- predict.lm(model)

for (X in varlist) {
print(X)
A <- na.omit(DF[,c(X,Y)])
P <- na.omit(DF[,c(X,P.Y)])
plot(A)
points(P,col=2)
lines(lowess(A,f=smooth),col=1)
lines(lowess(P,f=smooth),col=2)
}

}
PvA(my_model)

• have you tried plot on the lm or glm object? How what you are trying to achieve is different from what plot.lm does? Feb 18, 2011 at 8:29
• @mpiktas I'm looking for something to supplement plot.lm or plot.glm. Plot.lm shows residuals vs Fitted, Scale-Location, Normal Q-Q and Residuals vs. leverage plots. What I'm looking for is plots of the actual relationship between Solar.R and and Ozone, and the predicted relationship from my model. Run my example code, and you will see what I mean.
– Zach
Feb 18, 2011 at 14:33

In addition to @mpiktas's comment, you can also have a look at the rms package from Frank Harrell. The advantage is that it handles both LM and GLM for model fitting and prediction; see for example the plot.Predict() function. If you're planning to do serious job in regression modeling, this package and its companion Hmisc are really good.