Align grob at fixed top/center position, regardless of size

China☆狼群 提交于 2019-11-27 06:26:37

问题


I have some table grobs, some long and some short. I'd like to draw these at the top/center of the page (with a small margin).

From this answer, I got a helpful starting point, but the positioning is dependent on each grob's height.

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

I've been experimenting with different parameters to the viewport call -- e.g.

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

but haven't been successful. Any help appreciated!


回答1:


using the code from the other answer, I get this

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)


来源:https://stackoverflow.com/questions/32106333/align-grob-at-fixed-top-center-position-regardless-of-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!