4

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)

enter image description here

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().

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried your code, but it seems to produce the same plot as in my post. I need every line in the plot to be black
In your question you said that "make each random effect line the same colour as the colours displayed for cyl".
Apologies yes, answer accepted. Are you able to just delete these comments?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.