Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在固定的顶部/中心位置对齐grob,无论大小_R_R Grid_Gridextra - Fatal编程技术网

在固定的顶部/中心位置对齐grob,无论大小

在固定的顶部/中心位置对齐grob,无论大小,r,r-grid,gridextra,R,R Grid,Gridextra,我有几张桌子,一些长的,一些短的。我想把这些画在页面的顶部/中间(留一小页边距) 从中,我得到了一个有用的起点,但定位取决于每个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[

我有几张桌子,一些长的,一些短的。我想把这些画在页面的顶部/中间(留一小页边距)

从中,我得到了一个有用的起点,但定位取决于每个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]])

我一直在试验
视口调用的不同参数——例如


但是没有成功。感谢您的帮助

使用另一个答案中的代码,我得到了这个

库(gridExtra)

很遗憾,justify
grobHeight
没有给你一个准确的尺寸,使用
sum(g$heights)
应该可以更好地工作。你现在可以用以下方式调整
只是
(我的一个例子)
just=c(0.5,0.53)
谢谢,但我不是在同一页上画表格——我需要每个表格都在自己的页上,我只是把它们放在同一页上以示说明。@baptiste你怎么把它们放在页面的中心?
# 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]])
viewport(x = 0.5, y = unit(0.95, 'npc'), just=c('center', 'top'))
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)