Search code examples
rggplot2lme4lattice

Plot the random parts of the mixed effect output in ggplot2


I have run a model by lmer

library(lmer)
mymodel<- glmer(wrimm ~ 1+itr+(1+itr|GE_state), data=dt_n, family = binomial(link="logit"),control=glmercontrol(optimizer="bobyqa"),nAGQ=0)

and use dotplot to visualise the random effect (including intercepts and slopes)

re<-ranef(mymodel, which="GE_state", conVar=TRUE)
lattice::dotplot(re, scales = list(x =list(relation = 'free')))

and acquire this figure

enter image description here

However, the dotplot has only limited functions for aesthetics. I would appreciate if someone can tell me how to make the same plot (a "forest plot", with random effect coefficients and their confidence intervals) by ggplot2.

Thank you for helping a beginner.


Solution

  • The example in this page shows how to plot in ggplot 2 as the output of lattice::dotplot: https://rdrr.io/cran/lme4/man/ranef.html

    fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
    
    ranef(fm1)
    str(rr1 <- ranef(fm1))
    
    ## as.data.frame() provides RE's and conditional standard deviations:
    str(dd <- as.data.frame(rr1))
    if (require(ggplot2)) {
        ggplot(dd, aes(y=grp,x=condval)) +
            geom_point() + facet_wrap(~term,scales="free_x") +
            geom_errorbarh(aes(xmin=condval -2*condsd,
                               xmax=condval +2*condsd), height=0)