This post serves as a sample of how to use ggplot to plot key graphs for regression.
The model that is produced by lm() is a type of data set, which has variables in it. One of those variables is predicted values (or called fitted values). The fitted value can be accessed by modelNmae$fitted.values; it is a good idea to save these fitted values in the original data frame:
data$fitted <- model$fitted.values
Adjusted predicted value:
The computer calculates a new model without a particular case and then uses this new model to predict the value of the outcome variable for the case that was excluded. If a case does not exert a large influence over the model, then we would expect the adjusted predicted value to be similar to the predicted value when the case is included. Put it similarly, if a model is stable then the predicted value of a case should be the same regardless of whether or not that case was used to calculate the model.
Studentized residual:
Studentized residual = (The adjusted predicted value – the original observed value)/standard error
This residual can be compared across different regression analyses because it is measured in standard unit. It is very useful to assess the influence of a case on the ability of the model to predict that case. However, how a case influences the model as a whole can not be told by Studentized residual. Cook’s distance measures the overall influence of a case on the model.
Suppose we have studentized residuals saved in our original data frame, then we can plot a histogram of the studentized residuals.
# histogram
histogram <- ggplot(data, aes(studentized.residuals)) + opts(legend.position = "none") + geom_histogram(aes(y=..density..), color = "black", fill = "white") + labs(x="Studentized Residual", y="Density")
# density curve
histogram + stat_function(fun = dnorm, args = list(mean = mean(data$studentized.residuals), na.rm = TRUE), sd = sd(data$studentized.residuals, na.rm = TRUE)), color = "red", size = 1)
We can create a Q-Q plot.
qqplot.resid <- qplot(sample = data$studentized.residuals, stat = "qq") + labs(x = "Theoretical values", y="Observed values")
We can also plot a scatterplot of studentized residuals against predicted values:
scatter <- ggplot(data, aes(fitted, studentized.residuals))
scatter + geom_point() + geom_smooth(method="lm", color="Blue") + labs(x="Fitted value", y="Studentized Residual")