Question

If i make a simple mixed effects model with two random effects:

library(lme4)
(fm3 <- lmer(strength ~ 1 + (1 | batch) + (1 | sample), Pastes))

I can get acces to the random effects like so:

ranef(fm3)
ranef(fm3)$batch
ranef(fm3)$sample

I do not manage to plot the random effects in two separate dotplots next to each other. The following bit of code does draw both plots but i do not manage recode it so that i can plot each graph separately:

dotplot(ranef(fm3, postVar=TRUE))

The following seems logical to me but it is not correct

dotplot(ranef(fm3, postVar=TRUE)$batch)

thanks for all help,

Was it helpful?

Solution

The problem you have is that ranef() stores the result of your analysis as a list, not data frame. You are trying to access this list as you would access data frame, that's why it doesn't work. The trick is to use double square bracket with dotplot to access the list. Then you can use grid.arrange to quickly combine your plots (or you can use @juba solution).

library(lme4)
fm3 <- lmer(strength ~ 1 + (1 | batch) + (1 | sample), Pastes)
d1 <- ranef(fm3, postVar=TRUE)
#double square bracket access the lists in d1
a <- dotplot(d1)[["batch"]]
b <- dotplot(d1)[["sample"]]
#grid.arrange combines your plots
library(gridExtra)
grid.arrange(a,b, nrow=1) 

enter image description here

OTHER TIPS

The following bit of code does the trick:

print((dotplot(ranef(fm3, postVar=TRUE))$sample), position=c(0, .5, 1, 1), more=TRUE)
print((dotplot(ranef(fm3, postVar=TRUE))$batch), position=c(0, 0, 1, .5)

It came from the realisation that plotting the prediction intervals for just one of the two rando effects can be done through:

(dotplot(ranef(fm3, postVar=TRUE))$sample)

and

(dotplot(ranef(fm3, postVar=TRUE))$batch)

What i proposed above is wrong (dotplot(ranef(fm3, postVar=TRUE)$batch) even though it does produce something). @juba: thanks for pointing me towards lattice. the solution i found for combining plots is a bit more concise...

As dotplot is part of the lattice package, you have to play with grid.layout and viewports to display several plots on one graph.

Here is a way to display two dotplots side by side, but as I'm quite new to lattice there surely is a better and cleaner way to do it :

grid.newpage()
pushViewport(viewport(0.25,0.5,.5,1))
print(dotplot(rnorm(100)),newpage=FALSE)
upViewport()
pushViewport(viewport(.75,.5,.5,1))
print(dotplot(runif(100)),newpage=FALSE)

Which gives :

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top