简体   繁体   中英

using ggplot2 to plot mixed effects model

Code below plots random effects from a mixed effects model:

mtcarsSub <- mtcars[,c("wt", "drat", "cyl")]

library(lme4)
mtcarsME <- lmer(drat ~ (1|cyl) + wt, data=mtcarsSub)

mtcarsSub$fixed.effect <- predict(mtcarsME)

library(plyr)
l_ply(list(4, 6, 8), function(x) mtcarsSub[[ paste0("random.effect.cyl", x) ]] <<- mtcarsSub$fixed.effect + ranef(mtcarsME)$cyl[as.character(x),])

library(ggplot2)
ggplot(mtcarsSub, aes(wt, drat, color=factor(cyl))) + 
  geom_point() +
  geom_line(aes(wt, fixed.effect), color="black", size=2) +
  geom_line(aes(wt, random.effect.cyl4), size=2) +
  geom_line(aes(wt, random.effect.cyl6), size=2) +
  geom_line(aes(wt, random.effect.cyl8), size=2)

在此处输入图片说明

How can I programatically make each random effect line the same colour as the colours displayed for cyl ? Therefore, the random effect line for level 4 of cyl should be red, level 6 of cyl should be green and level 8 of cyl should be blue. I dont want to specify color="red" etc in geom_line() .

I would suggest to make new data frame for the random effects. For this I use function ldply() and the function you made to calculate random effects for each level. Additionally in this new data frame added column wt and cyl . wt will contain all wt values from mtcarsSub data frame repeated for each level. cyl will contain values 4, 6 and 8.

mt.rand<-ldply(list(4,6,8), function(x) data.frame(
  wt=mtcarsSub$wt,
  cyl=x,
  rand=mtcarsSub$fixed.effect + ranef(mtcarsME)$cyl[as.character(x),]))

Now for the plotting use new data frame in one geom_line() call. As the new data frame also has cyl column it will be assigned the colors as for points.

ggplot(mtcarsSub, aes(wt, drat, color=factor(cyl))) + 
  geom_point() +
  geom_line(aes(wt, fixed.effect), color="black", size=2)+
  geom_line(data=mt.rand,aes(wt,rand),size=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM