2015-11-17 43 views
2

我正在繪製多級模型(使用lme4軟件包)中的預測值。我可以使用Effect()功能成功完成此操作。如下圖所示:將lmer的預測值繪製爲單個繪圖

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

enter image description here

但是,我想現在這些相同的數據,與一個傳奇的單一情節。使用ggplots,我可以做到這一點;但是,我失去了誤差線,如下圖所示:

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

enter image description here

我怎樣才能重新創建第一個圖(帶誤差條)作爲一個單一的情節?

回答

2

如何:

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

順便說一句,請注意,這個特殊的模型是沒有意義的(既包括作爲固定因素和隨機項)!我希望你只使用它作爲一個例證...

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

的關鍵是使用as.data.frame()打開效果對象到一些有用的東西......

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