【问题标题】:vertical alignment of gridExtra tableGrob (R grid graphics/grob)gridExtra tableGrob 的垂直对齐(R 网格图形/grob)
【发布时间】:2014-08-22 17:30:41
【问题描述】:

在对齐网格图形对象时遇到了一些问题——我已经阅读了我能找到的所有文档,包括 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()

我希望由tableGrob(在make_table 函数中)生成的整个表格都位于grob 的顶部。现在它在 grob 内垂直和水平居中。我需要在拨打tableGrob 时这样做,还是在拨打arrangeGrob 时这样做?换一种方式问,如果上述内容不清楚,我怎样才能使整个表格(而不是其中的文本)对齐到其容器的顶部/底部/左侧/右侧?

谢谢!

【问题讨论】:

  • 您可能想查看grid 包本身。特别是 grid.layout 函数对于创建自定义大小的视口很有用。您的代码问题源于arrangeGrob,它将纸张分成两个大小相等的视口。一旦您习惯于在 grid 中设置视口布局,您就不会想错过它。
  • @SimonGarrangeGrob 是 grid.layout 的包装器,允许高度不等。
  • 真的吗?我没有意识到它也允许设置对齐方式。对不起,错误信息!
  • @SimonG 可以指定高度和宽度;对齐是另一个问题。在网格中处理对齐总是很尴尬。

标签: r gridextra


【解决方案1】:

试试这个,

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

【讨论】:

  • 正要投票,然后发现我已经在之前的访问中投票了。再次感谢
猜你喜欢
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多