【问题标题】:using ggplot2 to plot mixed effects model使用 ggplot2 绘制混合效应模型
【发布时间】:2013-06-17 18:02:40
【问题描述】:

以下代码绘制来自混合效应模型的随机效应:

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)

如何以编程方式使每个随机效果线的颜色与cyl 显示的颜色相同?因此,cyl 的第 4 级随机效果线应为红色,cyl 的第 6 级应为绿色,cyl 的第 8 级应为蓝色。我不想在geom_line() 中指定color="red" 等。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我建议为随机效应制作新的数据框。为此,我使用函数 ldply() 和您创建的函数来计算每个级别的随机效应。此外,在这个新数据框中添加了 wtcyl 列。 wt 将包含来自mtcarsSub 数据帧的所有wt 值,每个级别重复。 cyl 将包含值 4、6 和 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),]))
    

    现在在一个geom_line() 调用中使用新数据框进行绘图。由于新数据框也有 cyl 列,它将被分配颜色作为点。

    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)
    

    【讨论】:

    • 我试过你的代码,但它似乎产生了与我的帖子相同的情节。我需要情节中的每一行都是黑色的
    • 在您的问题中,您说“使每个随机效果线的颜色与 cyl 显示的颜色相同”。
    • 抱歉,是的,回答已接受。您可以删除这些 cmets 吗?
    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2020-03-18
    相关资源
    最近更新 更多