Using ggplot2 to build a mixed effects model

Below is the random effects code from the 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) 

enter image description here

How can I programmatically make each line of a random effect the same color as the colors displayed for cyl ? Therefore, the line of random effect for level 4 cyl should be red, level 6 of cyl should be green, and level 8 of cyl should be blue. I do not want to specify color="red" , etc. In geom_line() .

+4
source share
1 answer

I would suggest creating a new data frame for random effects. To do this, I use the ldply() function and the function you did to calculate random effects for each level. In addition, the wt and cyl column is added in this new data frame. wt will contain all wt values ​​from the 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, to geom_line() a graph, a new data frame is used in one call to geom_line() . Since the new data frame also has a cyl column, it will be assigned 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) 
+2
source

Source: https://habr.com/ru/post/1486665/


All Articles