Specify widths and heights of plots with grid.arrange

前端 未结 2 664
小鲜肉
小鲜肉 2020-12-02 10:55

I have three plots and I try to combine them with grid.arrange. The last plot should have a smaller height than the first two plots and all the plots should have the same wi

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 11:47

    with gtable you need to set the heights of the panels manually,

    g1 <- ggplotGrob(p1)
    g2 <- ggplotGrob(p2)
    g3 <- ggplotGrob(p3)
    
    library(gridExtra)
    g <- rbind(g1, g2, g3)
    
    set_panel_heights <- function(g, heights){
      g$heights <- grid:::unit.list(g$heights) # hack until R 3.3 comes out
      id_panels <- unique(g$layout[g$layout$name=="panel", "t"])
      g$heights[id_panels] <- heights
      g
    }
    
    g <- set_panel_heights(g, lapply(1:3, grid::unit, "null"))
    grid::grid.draw(g) 
    

    Although a bit verbose, this approach is more general than specifying relative heights: you can mix all sorts of grid units,

    grid::grid.newpage()
    g <- do.call(rbind, replicate(3, ggplotGrob(ggplot()), simplify = FALSE))
    g <- set_panel_heights(g, list(unit(1,"in"), unit(1,"line"), unit(1,"null")))
    grid::grid.draw(g) 
    

提交回复
热议问题