Plotting predicted values from lmer as a single pl

2020-06-07 01:44发布

I am working on graphing the predicted values from a multilevel model (using the lme4 package). I am able to do this successfully using the Effect() function. As shown below:

library(lme4)
library(effects)
m1=lmer(price~depth*cut+(1|cut),diamonds)
plot(Effect(c("cut","depth"),m1))

enter image description here

But, I want to present these same data as a single plot with a legend. Using ggplots, I can do this; but, I lose the error bars, as shown below:

ggplot(data.frame(Effect(c("cut","depth"),m1)),
       aes(x=depth,y=fit,color=cut,group=cut))+
  geom_line()

enter image description here

How can I recreate the first plot (with error bars) as a single plot?

标签: r ggplot2 lme4
1条回答
劳资没心,怎么记你
2楼-- · 2020-06-07 02:49

How about:

library(effects)
library(lme4)
library(ggplot2)
m1 <- lmer(price~depth*cut+(1|cut),diamonds)

By the way, note that this particular model makes no sense (factor included both as fixed and random term)! I hope you're only using it as an illustration ...

ee <- Effect(c("cut","depth"),m1) 

The key is using as.data.frame() to turn the effects object into something useful ...

theme_set(theme_bw())
ggplot(as.data.frame(ee),
       aes(depth,fit,colour=cut,fill=cut))+
    geom_line()+
     ## colour=NA suppresses edges of the ribbon
    geom_ribbon(colour=NA,alpha=0.1,
                            aes(ymin=lower,ymax=upper))+
     ## add rug plot based on original data
        geom_rug(data=ee$data,aes(y=NULL),sides="b")

enter image description here

查看更多
登录 后发表回答