rlme4lattice

How does lattice package in R create gridlines automatically?


In the context of linear mixed effects model, it is extremely useful to plot residuals vs. fitted values to check homoscedasticity (of residuals). When I am using lme4::plot.merMod to plot such a figure, if I understand correctly, lme4 uses lattice to produce the figure. For example, if we regress hp on mpg with carb (from tidyverse::mtcars) as random effects*, we get a following plot:

enter image description here

I don't know, however, how lattice comes up with grey-color horizontal and vertical gridlines and if they represent any statistical aspect about model fit. If lattice just divides the x- and y-axis in four equal parts with these gridlines, how can I achieve such equally-spaced gridlines that consider x- and y-axis range in a base R plot?

Code to reproduce the figure:

library(lme4)
library(tidyverse)
model <- lme4::lmer(data = mtcars, formula = mpg ~ hp + (1 | gear))
plot(model, aspect = 1)

*I am not concerned about correct model specification at the moment.


Solution

  • In base R, this can be done by using graphics::grid (as suggested by Prof. Bolker):

    library(lme4)
    library(tidyverse)
    library(broom.mixed)
    
    model <- lme4::lmer(data = mtcars, formula = mpg ~ hp + (1 | gear))
    data <- broom.mixed::augment(model)
    
    par(pty='s')    # to keep aspect ratio 1
    plot(data$.fixed, data$.resid)
    graphics::grid(nx = 4, lty = 1)
    

    Or by directly using:

    plot(data$.fixed, data$.resid, panel.first = grid(4, lty = 1))
    

    enter image description here