2

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

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

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!

Community
  • 1
  • 1
arvi1000
  • 9,393
  • 2
  • 42
  • 52
  • `grobHeight` is unfortunately not giving you an accurate size, using `sum(g$heights)` should work better – baptiste Aug 20 '15 at 03:53
  • you can now tweak ``just`` in the following way (an example from a plot of mine). ``just=c(0.5, 0.53)`` – PatrickT Apr 10 '18 at 09:10

1 Answers1

3

using the code from the other answer, I get this

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)
baptiste
  • 75,767
  • 19
  • 198
  • 294