在 grid.arrange 中使用 layout_matrix 时修复绘图区域宽度

Fixing plot area width when using layout_matrix in grid.arrange

我正在组合图块的小平面图。我希望每个瓷砖都是方形的,或者至少具有相同的高度和宽度。

到目前为止,我已经设法使用 layout_matrix 为每行瓷砖提供了相同的高度。尝试为每一列图块(跨图)固定相同的宽度时,我被卡住了。

一些基于 mtcars 的代码来尝试说明我的情节布局(实际数据方式更复杂):

library("tidyverse")
library("gridExtra")

df0 <- mtcars %>% 
  group_by(cyl) %>%
  count()

df1 <- mtcars %>% 
  rownames_to_column("car") %>%
  mutate(man = gsub("([A-Za-z]+).*", "\1", car))

g <- list()
for(i in 1:nrow(df0)){
  g[[i]] <- ggplot(data  =  df1 %>% filter(cyl == df0$cyl[i]), 
                   mapping = aes(x = "", y = car, fill = qsec)) +
    geom_tile() +
    facet_grid( man ~ .,  scales = "free_y", space = "free") +
    labs(x = "", y = "") +
    guides(fill = FALSE) +
    theme(strip.text.y = element_text(angle=0)) +
    coord_fixed()
}

m0 <- cbind(c(rep(1, df0$n[1]), rep(NA, max(df0$n) - df0$n[1])),
            c(rep(2, df0$n[2]), rep(NA, max(df0$n) - df0$n[2])),
            c(rep(3, df0$n[3]), rep(NA, max(df0$n) - df0$n[3])))
grid.arrange(grobs = g, layout_matrix =  m0)

生成此图(减去我的 MS Paint 技能):

据推测,条带文本和y轴中标签的不同长度导致绘图区域的宽度不同。不确定如何避免这种行为?我以为我可以在大 facet_grid 上创建,但我无法接近上面的布局布局。

事实证明这是一件相当棘手的事情。幸运的是,cowplot::plot_grid 已经可以进行导致列大小相等的对齐。我只是采用了该功能并去除了绒毛,并将高度与其通常使用的网格图案分离。我们最终得到了一个小的自定义函数来完成这项工作(所有功劳都归功于 Claus Wilke):

plot_grid_gjabel <- function(plots, heights) {
  grobs <- lapply(plots, function(x) {
    if (!is.null(x)) 
      cowplot:::ggplot_to_gtable(x)
    else NULL
  })
  num_plots <- length(plots)
  num_widths <- unique(lapply(grobs, function(x) {
    length(x$widths)
  }))
  num_widths[num_widths == 0] <- NULL
  max_widths <- do.call(grid::unit.pmax, 
                        lapply(grobs, function(x) { x$widths }))
  for (i in 1:num_plots) {
    grobs[[i]]$widths <- max_widths
  }
  width <- 1 / num_plots
  height <- heights / max(heights)
  x <- cumsum(width[rep(1, num_plots)]) - width
  p <- cowplot::ggdraw() 
  for (i in seq_along(plots)) {
    p <- p + cowplot::draw_grob(grid::grobTree(grobs[[i]]), x[i], 1 - height[i], 
                                width, height[i])
  }
  return(p)
}

我们可以简单地这样称呼它:

plot_grid_gjabel(g, df0$n)

导致: