【问题标题】:Fixing plot area width when using layout_matrix in grid.arrange在 grid.arrange 中使用 layout_matrix 时修复绘图区域宽度
【发布时间】:2016-09-27 06:27:56
【问题描述】:

我正在组合瓷砖的刻面图。我希望每个瓷砖都是方形的,或者至少采用相同的高度和宽度。

到目前为止,我已经设法使用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 上创建,但我无法接近上面情节的布局。

【问题讨论】:

    标签: r plot ggplot2 tile facet


    【解决方案1】:

    原来这是一件相当棘手的事情。幸运的是,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)
    

    导致:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多