如何使用 grid.arrange 在 gtable 中顶部对齐这些表?

How can I top align these tables in gtable using grid.arrange?

我有一个降价文档,使用一点 LaTeX 生成包含以下块的 .pdf:

grid.arrange(
  grobs = list(
    gtable_combine(
      gtable_add_grob(
        tableGrob(mtcars[1:3, 1:2], rows = NULL),
        grobs = segmentsGrob(y1 = unit(0, "npc"),
        gp = gpar(fill = NA, lwd = 2)),
        t = 1,
        l = 1,
        r = ncol(mtcars[1:3, 1:2])
        ),
      gtable_add_grob(
        tableGrob(mtcars[1:3, 1:2], rows = NULL),
        grobs = segmentsGrob(y1 = unit(0, "npc"),
        gp = gpar(fill = NA, lwd = 2)),
        t = 1,
        l = 1,
        r = ncol(mtcars[1:3, 1:2])
        ),
        along = 2), 
    gtable_add_grob(
      tableGrob(mtcars[1:8, 1:2], rows = NULL),
      grobs = segmentsGrob(y1 = unit(0, "npc"),
                           gp = gpar(fill = NA, lwd = 2)),
      t = 1,
      l = 1,
      r = ncol(mtcars[1:8, 1:2])
      )
    ),
  ncol = 2
  )

输出居中对齐,我希望它在顶部对齐。我的症结在于左侧已经是两个组合的 table,我似乎无法将该函数的输出嵌套到另一个 gtable_combine() 的 cal 中。我在 gridExtra 中使用 layout_matrix= 参数也没有任何运气,因为这在左边的两个 tables.

之间增加了大量的 space

怎么才能让左边的两个table靠的很近(连在一起就好),而且还有最左边的顶端table和右边的顶端table水平对齐?

尝试

library(gridExtra)

t1 <- tableGrob(mtcars[1:3,], rows = NULL)
t2 <- tableGrob(mtcars[1:8,], rows = NULL)

grid.draw(gtable_combine(t1, t2))

enter image description here

我从 prior SO post 中找到了答案。在我看来,两个较短的 tables gtable_combine(...) 的输出的填充与较长的 table 的输出不同,因为顶部填充默认是长度的函数table,这里的两个 table,即使组合在一起,长度也会不同。 @baptiste 在他的回答中概述的函数通过修复该填充值解决了这个问题。在我的用例中实现它如下所示:

justify <- function(x, hjust="center", vjust="top", draw=FALSE){
  w <- sum(x$widths)
  h <- sum(x$heights)
  xj <- switch(
    hjust,
    center = 0.5,
    left = 0.5 * w,
    right = unit(1, "npc") - 0.5 * w
    )
  yj <- switch(
    vjust,
    center = 0.5,
    bottom = 0.5 * h,
    top = unit(1, "npc") - 0.5 * h
    )
  x$vp <- viewport(x=xj, y=yj)
  if(draw) grid.draw(x)
  return(x)
}

grid.arrange(
  justify(
    gtable_combine(
      gtable_add_grob(
        tableGrob(mtcars[1:3, 1:2], rows = NULL),
        grobs = segmentsGrob(y1 = unit(0, "npc"),
                             gp = gpar(fill = NA, lwd = 2)),
        t = 1,
        l = 1,
        r = ncol(mtcars[1:3, 1:2])
        ),
      gtable_add_grob(
      tableGrob(mtcars[1:3, 1:2], rows = NULL),
      grobs = segmentsGrob(y1 = unit(0, "npc"),
                           gp = gpar(fill = NA, lwd = 2)),
      t = 1,
      l = 1,
      r = ncol(mtcars[1:3, 1:2])
      ),
      along = 2
      )
    ), 
  justify(
    gtable_add_grob(
      tableGrob(mtcars[1:8, 1:2], rows = NULL),
      grobs = segmentsGrob(y1 = unit(0, "npc"),
                           gp = gpar(fill = NA, lwd = 2)),
      t = 1,
      l = 1,
      r = ncol(mtcars[1:3, 1:2])
      )
    ),
  ncol = 2
  )