我有一些桌子,有些长,有些短。我想在页面的顶部/中心绘制这些内容(边距很小)。
从this answer开始,我得到了一个有用的起点,但定位取决于每个grob的高度。
library(gridExtra)
# fake data
my_df <- data.frame(col1=rep('hello', 35), col2=round(rnorm(35), 3))
# list of grobs
tg <- list(tableGrob(my_df[1:30, ]), tableGrob(my_df[31:35, ]))
# this positions grobs at center top, but varies based on rows in table
tg[[1]]$vp <- viewport(x = 0.5,
y = unit(1,"npc") - 0.52 * grobHeight(tg[[1]]))
tg[[2]]$vp <- viewport(x = 0.5,
y = unit(1,"npc") - 0.52 * grobHeight(tg[[2]]))
# this one appears just below top, which is good
grid.newpage()
grid.draw(tg[[1]])
# this appears slightly closer to the top; desired outcome is to have column headers
# in same position as the previous one
grid.newpage()
grid.draw(tg[[2]])
我一直在试验viewport
电话的不同参数 - 例如
viewport(x = 0.5, y = unit(0.95, 'npc'), just=c('center', 'top'))
但尚未成功。任何帮助表示赞赏!
答案 0 :(得分:2)
使用其他答案中的代码,我得到了这个
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)