rangeGrob

时间:2018-11-08 15:40:57

标签: r gridextra gtable

我正在尝试构建一个包含多个页面的报告。每个页面具有相同的结构,标题说明正在显示的医院,然后在页面的上半部分有一个表格,在下半部分有一个图表。我正在使用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()

我的问题是,页面顶部有很多空间,表格底部被绘图所切除。

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

1 个答案:

答案 0 :(得分:0)

这里是一种可能性:查询表的高度(由内容决定的固定数字),其余部分留给绘图。请注意,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))