verticaly center table grobs in rmarkdown pdf

試著忘記壹切 提交于 2021-02-11 14:54:59

问题


I want to have my table grobs aligned to the top of each other but verticaly centered to the page with respect to the longest table. I need this to be automatic with tables of different lengths. This is what I have to vertically align them with each other as shown by @baptiste here.

---
output: pdf_document
geometry: 
  - paperwidth=13.333in
  - paperheight=7.5in
  - margin=.5in
---

```{r, echo=F, fig.align='center'}
library(magrittr)
library(gridExtra)
library(gtable)
library(grid)


# from https://stackoverflow.com/a/32111143/
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)
}

t1 <- cars %>%
  head() %>% 
  tableGrob()

t2 <- cars %>% 
  head(15) %>% 
  tableGrob()


tables <- list(t1, t2) %>% 
  lapply(justify, vjust="top", hjust ="left",  draw = F) %>% 
  arrangeGrob(grobs = ., nrow = 1)

grid.newpage()
grid.draw(tables)
```

I thought that if I just put my vertically aligned tables in a one-cell table grob with the same height as the page that it would vertically center them automatically.


```{r, echo=F, fig.align='center'}
grid.newpage()
gtable(widths = unit(10, "in"),
       # 6.5 inches is the page height minus the margins
       heights =  unit(6.5, "in")) %>%
  gtable_add_grob(tables, t = 1, l = 1, clip = "off") %>%
  grid.draw()
showViewport()
```

It just makes it worse! Plus the table grob I made to put tables into isn't the height it should be.

来源:https://stackoverflow.com/questions/60661723/verticaly-center-table-grobs-in-rmarkdown-pdf

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