无论大小如何,都将固定顶部/中心位置的凹槽对齐

时间:2015-08-19 21:58:55

标签: r r-grid gridextra

我有一些桌子,有些长,有些短。我想在页面的顶部/中心绘制这些内容(边距很小)。

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]])

enter image description here

# 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]])

enter image description here

我一直在试验viewport电话的不同参数 - 例如

viewport(x = 0.5, y = unit(0.95, 'npc'), just=c('center', 'top'))

但尚未成功。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

使用其他答案中的代码,我得到了这个

enter image description here

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)