Arrange ggplot plots (grobs with same widths) using gtable to create 2x2 layout

前端 未结 3 639
难免孤独
难免孤独 2021-02-01 11:14

I am attempting to use grobs and gtable to arrange 4 (ggplot2) plots into a 2x2 grid. I don\'t know how to set widths, and also a non- 1xn, or nx1 arrangement.

Using thi

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 11:57

    Pretty similar to the above, but using gtable functions*

    library(ggplot2)
    pl <- list(ggplot() + xlab("x"), 
               ggplot() + ylab("y"), 
               ggplot() + ylab("y"), 
               ggplot() + ggtitle("title") + xlab("x"))
    
    library(grid)
    library(gridExtra)
    
    gl <- lapply(pl, ggplotGrob)
    # gt <- cbind(rbind(gl[[1]], gl[[3]]),
    #            rbind(gl[[2]], gl[[4]]))
    
    #  alternative to remove x-axes of top row of plots
    gt <- cbind(rbind(gl[[1]][1:3,], gl[[3]]),
                rbind(gl[[2]][1:3,], gl[[4]]))
    
    grid.newpage()
    grid.draw(gt)
    

    *: actually, since gtable doesn't allow the use of pmax when comparing units, this is using a drop-in replacement from the dev version of gridExtra.

提交回复
热议问题