Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用ggplot2绘制混合效果模型_R_Ggplot2 - Fatal编程技术网

R 使用ggplot2绘制混合效果模型

R 使用ggplot2绘制混合效果模型,r,ggplot2,R,Ggplot2,下面的代码绘制混合效果模型的随机效果: 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[[ pa

下面的代码绘制混合效果模型的随机效果:

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)

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

我试过你的代码,但它似乎产生了与我的文章相同的情节。我需要情节中的每一行都是黑色的。在你的问题中,你说过“让每一条随机效果线的颜色与为共青团显示的颜色相同”。抱歉是的,回答被接受。你能删除这些评论吗?
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)