【问题标题】:Vertical justification and heights in arrangeGrob排列Grob中的垂直对齐和高度
【发布时间】:2018-11-08 15:40:57
【问题描述】:

我正在尝试构建一个包含多个页面的报告。每一页都有相同的结构,一个标题说明显示的是哪家医院,然后是页面上半部分的表格和下半部分的图表。我正在使用tableGrob 将表格转换为图形对象,并使用arrangeGrob 将其全部放入页面中。我的代码看起来像:

library(ggplot2)
library(gridExtra)
library(grid)
library(gtable)

df <- iris[1:10,]
pp <- ggplot(iris, aes(x = Sepal.Length)) + geom_histogram(binwidth = 0.2)

tTitle <- textGrob(paste("Title line 1","\n", "Line 2", "\n", "Line 3"),
                   gp=gpar(fontsize=15))
padding <- unit(3,"line")
tt <- tableGrob(df, rows = NULL, theme = ttheme_minimal())
tt <- gtable_add_rows(tt, heights = grobHeight(tTitle) + padding, pos = 0)
tt <- gtable_add_grob(tt, list(tTitle), t=1, l=1, r=ncol(tt))

pg <- arrangeGrob(tt, pp,
                  nrow=2, as.table=FALSE)

pdf("Demo.pdf", paper = "a4", width = 8.27)
grid.draw(pg)
dev.off()

我的问题是页面顶部有很多空间,表格底部被情节切断了。

如何垂直对齐标题和表格,以便它们向上移动页面,为绘图留出足够的空间?

【问题讨论】:

    标签: r gridextra gtable


    【解决方案1】:

    这里有一种可能性:查询表格的高度(由内容决定的固定数字),其余的留给绘图。请注意,paper="a4" 引入了它自己的特性,我会省略它。

    library(ggplot2)
    library(gridExtra)
    library(grid)
    library(gtable)
    library(maggritr)
    
    df <- iris[1:10,]
    pp <- ggplot(iris, aes(x = Sepal.Length)) + geom_histogram(binwidth = 0.2)
    
    tTitle <- textGrob(paste("Title line 1","\n", "Line 2", "\n", "Line 3"),
                       gp=gpar(fontsize=15))
    padding <- unit(3,"line")
    
    tt <- tableGrob(df, rows = NULL, theme = ttheme_minimal()) %>%
      gtable_add_rows(heights = grobHeight(tTitle) + padding, pos = 0) %>%
      gtable_add_grob(list(tTitle), t=1, l=1, r=ncol(tt)) %>%
      gtable_add_grob(rectGrob(gp=gpar(fill=NA,col="red")),
                      t=1, l=1, r=ncol(tt),b=nrow(tt))
    
    th <- sum(tt$heights)
    pg <- arrangeGrob(tt, pp, heights = unit.c(th, unit(1,"npc")-th))
    
    pdf("Demo.pdf", width=21/2.54,height=27.7/2.54)
    grid.draw(pg)
    dev.off()
    

    请注意,使用这种方法,ggplot 将扩展以填充剩余空间。如果你不想这样,你应该指定一个固定的高度,例如

    # 10 cm or remaining space on the page if smaller than that
    cappedheight = unit.pmin(unit(1,"npc"), unit(10, "cm"))
    # wrap plot in a grobTree to assign a viewport (centered in remaining space)
    pp1 <- grobTree(ggplotGrob(pp), vp=viewport(height=cappedheight))
    pg <- arrangeGrob(tt, pp1, heights = unit.c(th, unit(1,"npc")-th))
    

    【讨论】:

    • 谢谢。我将在星期一使用真正的桌子尝试这个并接受答案,然后如果它解决了我的问题。
    猜你喜欢
    • 2014-07-21
    • 2015-05-26
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多