Plot random effects from lmer (lme4 package) using qqmath or dotplot: How to make it look fancy?

前端 未结 4 1947
耶瑟儿~
耶瑟儿~ 2020-12-07 08:46

The qqmath function makes great caterpillar plots of random effects using the output from the lmer package. That is, qqmath is great at plotting the intercepts from a hiera

4条回答
  •  离开以前
    2020-12-07 09:14

    One possibility is to use library ggplot2 to draw similar graph and then you can adjust appearance of your plot.

    First, ranef object is saved as randoms. Then variances of intercepts are saved in object qq.

    randoms<-ranef(fit1, postVar = TRUE)
    qq <- attr(ranef(fit1, postVar = TRUE)[[1]], "postVar")
    

    Object rand.interc contains just random intercepts with level names.

    rand.interc<-randoms$Batch
    

    All objects put in one data frame. For error intervals sd.interc is calculated as 2 times square root of variance.

    df<-data.frame(Intercepts=randoms$Batch[,1],
                  sd.interc=2*sqrt(qq[,,1:length(qq)]),
                  lev.names=rownames(rand.interc))
    

    If you need that intercepts are ordered in plot according to value then lev.names should be reordered. This line can be skipped if intercepts should be ordered by level names.

    df$lev.names<-factor(df$lev.names,levels=df$lev.names[order(df$Intercepts)])
    

    This code produces plot. Now points will differ by shape according to factor levels.

    library(ggplot2)
    p <- ggplot(df,aes(lev.names,Intercepts,shape=lev.names))
    
    #Added horizontal line at y=0, error bars to points and points with size two
    p <- p + geom_hline(yintercept=0) +geom_errorbar(aes(ymin=Intercepts-sd.interc, ymax=Intercepts+sd.interc), width=0,color="black") + geom_point(aes(size=2)) 
    
    #Removed legends and with scale_shape_manual point shapes set to 1 and 16
    p <- p + guides(size=FALSE,shape=FALSE) + scale_shape_manual(values=c(1,1,1,16,16,16))
    
    #Changed appearance of plot (black and white theme) and x and y axis labels
    p <- p + theme_bw() + xlab("Levels") + ylab("")
    
    #Final adjustments of plot
    p <- p + theme(axis.text.x=element_text(size=rel(1.2)),
                   axis.title.x=element_text(size=rel(1.3)),
                   axis.text.y=element_text(size=rel(1.2)),
                   panel.grid.minor=element_blank(),
                   panel.grid.major.x=element_blank())
    
    #To put levels on y axis you just need to use coord_flip()
    p <- p+ coord_flip()
    print(p)
    

    enter image description here

提交回复
热议问题