gridExtra tableGrob(R grid graphics/grob)的垂直对齐方式

And*_*rew 4 r gridextra

在对齐网格图形对象时遇到一些麻烦 - 已经阅读了我能找到的所有文档,包括Murrell书籍,但没有成功.我认为我想做的事情非常简单,所以希望我很简单.

这是一个可重现的例子,它将在Hadley的hflights包中按目的地制作所有航空承运人的PDF (反映我在不同的数据集上尝试做的事情).

require(hflights)
require(gridExtra)
require(Cairo)

make_table <- function(df) {
  p <- tableGrob(
    df
   ,padding.h=unit(.25, "mm")
   ,show.rownames=FALSE
   ,gpar.coretext = gpar(fontsize=8, lineheight=0)
   #this doesn't seem to justify the table
   ,just = c("bottom")
   ,show.box = T
  )
  return(p)
}

dests <- unique(hflights$Dest)

#list to hold the plots
plot_list <- list()

#loop over destinations and make a simple report
for (i in dests) {
  #just this destination
  this_dest <- hflights[hflights$Dest == i, ]

  #the title
  title <- textGrob(label = i, gp = gpar(fontsize=72, fontface = 'bold'))

  #a table of carriers
  carriers <- unique(this_dest$UniqueCarrier)
  carriers <- data.frame(
    carrier=carriers  
  )
  carrier_table <- make_table(carriers)

  #put them together
  p <- arrangeGrob(
    title, carrier_table
   ,nrow=2
  )

  plot_list[[i]] <- p
}


#print the report
Cairo(
  width = 11, height = 8.5 
 ,file = paste('destinations.pdf', sep = ''), type="pdf"
 ,units = "in"
)

  print(plot_list)

dev.off()
Run Code Online (Sandbox Code Playgroud)

我希望tableGrob(在make_table函数中)生成的整个表格合理到grob的顶部.现在它垂直和水平地居中在grob内.我是否需要在通话中这样做tableGrob,或者是否在arrangeGrob通话中?换句话说,如果上述情况不明确,我怎样才能使整个表格(而不是其中的文字)与其容器的顶部/底部/左/右对齐?

谢谢!

bap*_*ste 7

试试这个,

在此输入图像描述

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

g <- tableGrob(iris[1:3,1:2])
grid.newpage()
justify(g,"right", "top")
Run Code Online (Sandbox Code Playgroud)