Search code examples
rplotdata-visualizationmodel-checking

Plotting residuals vs. remaining variables


Currently I am using a script based on the pairs command in R to find the relationship between the residuals of a given model and the remaining variables. This relationship can be important for model diagnostics. You can see my code below for a small example of how I am currently plotting the relationship.

If I have many variables (say ~10) in my model then the pairs plot becomes quite large. I am only looking at the bottom row of the pairs plot with the relationship with the residuals and the plot could therefore be simplified greatly. Can anyone recommend a command to plot only the bottom row of the pairs plot or something similar?

It would be great if the new plotting method could use a grid for the residual analysis instead of having a very wide plot.

gpa <- read.delim("GPA.txt", dec = ",")
mod <- lm(CGPA ~ HSGPA + Studytime, data = gpa)
pairs(cbind(gpa, residuals(mod)), panel=panel.smooth)
dput(gpa)

Output from dput(gpa)

structure(list(Studytime = c(7, 2, 4, 3.5, 4.5, 3, 3, 8, 5.5, 
5.5, 5, 7, 9, 4, 10, 3, 3, 3.5, 4.5, 3.5, 2, 6, 6, 4, 3, 4, 10, 
4.5, 7, 5, 3, 8, 5, 8, 4.5, 2, 3, 6, 10, 2, 12, 5, 4, 3, 4, 4, 
4, 5, 15, 4.5, 4, 4, 5, 5, 6, 3, 3, 2, 2.3), HSGPA = c(3.9, 3.79, 
3, 3.9, 3.6, 3.2, 3.78, 3.2, 3.5, 3.8, 3.89, 3.8, 4, 3.3, 3.7, 
3.9, 3.5, 3.9, 4, 3.5, 3.79, 3.9, 3.5, 3.8, 4, 3.5, 2.55, 3.8, 
4, 4, 4, 3.8, 4, 4, 4, 4, 4, 3.86, 4, 4, 3.9, 4, 4, 4, 4, 4, 
4, 4, 4, 3.7, 3.75, 3.94, 3.9, 3.9, 4, 3.97, 4, 4, 3.6), CGPA = c(3.3, 
3.13, 3.6, 3.5, 3.5, 3.75, 3.47, 2.8, 2.88, 3.28, 3.53, 3.5, 
3.98, 2.6, 3.5, 3.98, 3.75, 3.67, 3.75, 3.9, 3.1, 3.14, 3.8, 
3.7, 3.87, 3.31, 3.14, 2.98, 4, 3.77, 4, 3.49, 3.99, 3.78, 3.92, 
3.77, 3.83, 3.86, 3.86, 3.93, 3.91, 4, 3.73, 3.75, 3.99, 3.8, 
3.77, 3.95, 3.74, 3.65, 3.83, 4, 3.2, 3.6, 3.75, 3.77, 3.83, 
3.7, 2.5)), .Names = c("Studytime", "HSGPA", "CGPA"), class = "data.frame", row.names = c(NA, 
-59L))

Solution

  • To plot the residuals (y-axis) against the other variables and to include the panel.smooth method, you can use the following code, which gives n ( in this case 3) different plots:

    # plotting just the lowest plots
    sapply(1:ncol(gpa), function(i) {
      plot(x = gpa[, i], y = residuals(mod), xlab = names(gpa)[i])
      panel.smooth(x = gpa[, i], y = residuals(mod))
    })
    

    If you want to have the plots on one page you can adjust it with par(mfrow = c(2,2)) (which gives a plot matrix of 2x2).