不管大小如何,将握把对准顶部/中心的固定位置 [英] Align grob at fixed top/center position, regardless of size

查看:110
本文介绍了不管大小如何,将握把对准顶部/中心的固定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些桌子杂货,有些长,有些短.我想在页面的顶部/中央绘制这些内容(边距很小).

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

此答案,我得到了一个有用的起点,但其位置取决于每个grob的高度.

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

我一直在尝试对viewport调用使用不同的参数-例如

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!

推荐答案

使用其他答案中的代码,我明白了

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)

这篇关于不管大小如何,将握把对准顶部/中心的固定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆