r - 在 pdf 顶部排列 tableGrob

标签 r pdf gridextra

<分区>

我想将 tableGrob 图表与 pdf 的顶部对齐。默认设置为中间。我的问题是图表的行号不同。

library(ggplot2)

g <- gridExtra::tableGrob(head(iris))
g2 <- gridExtra::tableGrob(iris[1:3,])

pdf("test.pdf")
gridExtra::grid.arrange(g, heights = c(1,3), padding = unit(1,"in"), top = 
"Title")
gridExtra::grid.arrange(g2, heights = c(1,3), padding = unit(1,"in"), top = 
"Title2")

dev.off()

标题和图表之间的间距不一致。 "Title2"和 g2 之间的空间比 "Title"和 g 大得多。我怎样才能将这两个图表“锁定”到距页面顶部 1.5 英寸?最终,我会有很多行号不同的图表,并且不想每次都手动更改“高度”参数。

pdf page 1 pdf page 2 enter image description here enter image description here

最佳答案

关于同一主题有多个问题,所有其他问题的公认答案是 Post from Baptiste

library(gridExtra)
justify <- function(x, hjust="center", vjust="center", draw=TRUE){
  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)
}

library(gridExtra)

tg <- list(tableGrob(iris[1:3, 1:2]), tableGrob(iris[1:5, 1:2]))
tgt <- lapply(tg, justify, vjust="top", draw=FALSE)
grid.newpage()
grid.arrange(grobs=tgt, ncol=2)

在您的情况下,您会在 PDF 代码中放置适当的 grid.arrange()。

我会提到,当我尝试这样做时,我确实遇到了以下错误:

5.stop("both operands must be units")
4.Ops.unit(unit(1, "npc"), 0.5 * h)
3.FUN(X[[i]], ...)
2.lapply(myplot, justify, vjust = "top", draw = FALSE)

如果你遇到同样的错误,也许有人可以对此发表评论。

关于r - 在 pdf 顶部排列 tableGrob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901312/

相关文章:

r - 在 R 中使用很长的字符串创建公式

c++ - 自制礼帽 : looks the same but not identical

r - dplyr 和带有 summarise 的聚合;一种在不同聚合级别获取平均值的简单方法

php - 如何验证文件和变量字符串的 mime 类型(例如 PDF)?

r - 如何使用 R 中的 grid.arrange 在并排排列的图周围绘制框/边框

r - ggplot2:使用grid.arrange()作为do.call()的参数定义图版面

r - 由于逐条记录插入,使用 dbWritetable 使用 RJDBC 写入 SAP HANA 非常慢

r - knitr 没有将 pdf 输出中的数字对齐到中心——替代方案?

php - 如何使用 PHP 制作 pdf 文件

r - 如何将条形图绘制到 ggplot2 map 上