我想将 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
关于同一主题有多个问题,所有其他问题的公认答案是 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)
如果你遇到同样的错误,也许有人可以对此发表评论。