J.Karl
J.Karl

Reputation: 45

Plotting random effects with lmer and sjPlot

I am currently running a mixed effects model using lmer in which random slopes and correlated random intercepts are estimated. After fitting the model I would like to plot the result allowing from random slopes and intercepts as well as one overall fixed line. How I currently implement is this way:


library(lmer)
library(sjPlot)

df <- read_csv("anonymized_test.csv")
m1 <- lmer("DV ~ IV + (1 + IV| iso)", df) 

plot_model(m1, ,type="pred",
           terms=c("IV","iso"),
           pred.type="re", ci.lvl = NA)

This is the result: enter image description here

Which is not what is expected as we would expect some negative and positive slopes in addition to the random intercepts according to the extracted random effects of the model enter image description here

The problem is that sjPlot seems to only plot the random intercepts. Looking at an older vignette of sjPlot this seems to have been implemented in a deprecated function (see here ). The question is how do I get this functionality back? Thanks for any insight.

Upvotes: 1

Views: 4765

Answers (1)

jay.sf
jay.sf

Reputation: 73612

This is actually straightforward, even without the sjPlot package. We may extract fixef and ranef as fe and re and combine them in a plot. Both, fe and re have intercept and slope and get added together.

library(lme4)
fm1 <- lmer("Reaction ~ Days + (Days | Subject)", sleepstudy)

fe <- fixef(fm1)
re <- ranef(fm1)$Subject

clr <- rainbow(nrow(re))  ## define n colors

par(mfrow=c(1, 2))

plot(Reaction ~ Days, sleepstudy, col=clr[as.numeric(Subject)], main='Pred w/ points')
lapply(seq_len(nrow(re)), \(x) abline(fe[1] + re[x, 1], fe[2] + re[x, 2], col=clr[x]))

plot(Reaction ~ Days, sleepstudy, col=clr[as.numeric(Subject)], main='Pred w/o points', type='n')
lapply(seq_len(nrow(re)), \(x) abline(fe[1] + re[x, 1], fe[2] + re[x, 2], col=clr[x]))

enter image description here

However, I also get the random slopes using sjPlot. Not sure what went wrong, maybe you are using outdated software?

sjPlot::plot_model(fm1, type="pred", terms=c("Days","Subject"), pred.type="re", ci.lvl=NA)
# Warning message:
# In RColorBrewer::brewer.pal(n, pal) :
#   n too large, allowed maximum for palette Set1 is 9
# Returning the palette you asked for with that many colors

enter image description here

Upvotes: 4

Related Questions