Setting absolute size of facets in ggplot2

后端 未结 1 629
旧巷少年郎
旧巷少年郎 2020-11-28 12:39

I\'m creating several facetted plots for a report. The number of facets varies between 2 and 8. Ideally, I\'d like the absolute size of each facet (across plots) to be the s

相关标签:
1条回答
  • 2020-11-28 13:26

    I've used the following function for this purpose,

    set_panel_size <- function(p=NULL, g=ggplotGrob(p), file=NULL, 
                               margin = unit(1,"mm"),
                               width=unit(4, "cm"), 
                               height=unit(4, "cm")){
    
      panels <- grep("panel", g$layout$name)
      panel_index_w<- unique(g$layout$l[panels])
      panel_index_h<- unique(g$layout$t[panels])
      nw <- length(panel_index_w)
      nh <- length(panel_index_h)
    
    if(getRversion() < "3.3.0"){
    
       # the following conversion is necessary
       # because there is no `[<-`.unit method
       # so promoting to unit.list allows standard list indexing
       g$widths <- grid:::unit.list(g$widths)
       g$heights <- grid:::unit.list(g$heights)
    
       g$widths[panel_index_w] <-  rep(list(width),  nw)
       g$heights[panel_index_h] <- rep(list(height), nh)
    
    } else {
    
       g$widths[panel_index_w] <-  rep(width,  nw)
       g$heights[panel_index_h] <- rep(height, nh)
    
    }
    
      if(!is.null(file))
        ggsave(file, g, 
               width = grid::convertWidth(sum(g$widths) + margin, 
                                    unitTo = "in", valueOnly = TRUE),
               height = grid::convertHeight(sum(g$heights) + margin,  
                                      unitTo = "in", valueOnly = TRUE))
    
      g
    }
    
    g1 <- set_panel_size(plot1)
    g2 <- set_panel_size(plot2)
    gridExtra::grid.arrange(g1,g2)
    

    0 讨论(0)
提交回复
热议问题