1

我有一个降价文档,使用一点 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
  )

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

我怎样才能让左边的两张桌子非常接近(相邻的很好),并且最左边的桌子的顶部和右边的桌子的顶部水平对齐?

4

2 回答 2

0

尝试

library(gridExtra)

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

grid.draw(gtable_combine(t1, t2))

在此处输入图像描述

于 2018-01-24T12:07:21.967 回答
0

我已经从之前的 SO 帖子中找到了答案。在我看来,两个较短表格gtable_combine(...)的输出的填充与较长表格的输出不同,因为顶部填充默认情况下是表格长度的函数,这里这两个表格,即使组合在一起,也会长度不同。@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
  )
于 2018-01-29T15:58:38.680 回答