3

I want to align a tableGrob chart to the top of a pdf. The default setting is the middle. My issue is when I have charts with different row numbers.

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

The spacing between the titles and charts is not consistent. The space between "Title2" and g2 is much greater than "Title" and g. How can I "lock" both charts to, say, 1.5 in. from the top of the page? Ultimately, I will have lots of charts with varying row numbers and do not want to change the "heights" argument manually each time.

pdf page 1 pdf page 2 enter image description here enter image description here

Tung
  • 26,371
  • 7
  • 91
  • 115

1 Answers1

0

There have been multiple questions about this same topic, and the accepted answer on all the others is this 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)

In your case, you would place the appropriate grid.arrange() inside your PDF code.

I will mention that when I tried this, I do get the following error:

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)

If you get the same error, perhaps someone can comment on this.