user53330 user53330 - 11 months ago 107
R Question

R lme4 Plot lmer residuals ~ fitted by Factors levels in ggplot

I would like to reproduce lmer diagnostic plots in ggplot2. Particularly, I know that for a lmer model

DV ~ Factor1 * Factor2 + (1|SubjID)
I can simply call
plot(model, resid(.)~fitted(.)|Factor1+Factor2)
to generate a lattice-based Residuals Vs. Fitted plot, faceted for each Factor1+Factor 2 combination.

I would like to generate the same plot, but using ggplot2. I tried using
qplot(resid(model), fitted(model))
and different variations of that with different arguments, but the information about the factors needed for faceting is not coming through with this (and similar) calls.

I'd appreciate any advise to achieve this, thanks!

The core of my question: given any lmer model, how can I create a data-frame including fitted and residual values AND the Factor information for each value? something like:

Factor1 Factor2 Fitted Resid
0 0 987 654
0 0 123 456

I could not figure that out from lmer documentation on the

Answer Source

Here is an example of what we want, a reproducible example

data(Orthodont, package="nlme")
Orthodont$age <- as.factor(Orthodont$age)

model <- lmer(distance ~ age * Sex + (1|Subject), Orthodont)
plot(model, resid(.) ~ fitted(.) | age + Sex )


ggplot(model, aes(.fitted, .resid)) + geom_point() +
  facet_wrap(~ Sex + age, ncol = 4)    # (edited) I noticed fortify(model) isn't necessary.