使用r中的grid.table打印到pdf文件 - 太多行以适合一页

use*_*978 11 pdf r gridextra

我正在尝试使用GridExtra包中的grid.table将大约40行和5列的数据帧输出到.pdf文件.

但是,对于页面来说,40行太长,因此.pdf文件只显示数据帧的一部分.我想知道我是否可以在一个页面上打印两列,以便所有行显示在一个页面上.或者,我需要知道如何在多个页面上打印数据帧.谢谢,约翰

bap*_*ste 6

我建议采用以下策略:创建 tableGrob,查询其高度,拆分行以适合每个页面,

library(gridExtra)
library(grid)
d <- iris[sample(nrow(iris), 187, TRUE),]
tg <- tableGrob(d, rows = seq_len(nrow(d))) 

fullheight <- convertHeight(sum(tg$heights), "cm", valueOnly = TRUE)
margin <- unit(0.51,"in")
margin_cm <- convertHeight(margin, "cm", valueOnly = TRUE)
a4height <- 29.7 - margin_cm
nrows <- nrow(tg)
npages <- ceiling(fullheight / a4height)

heights <- convertHeight(tg$heights, "cm", valueOnly = TRUE) 
rows <- cut(cumsum(heights), include.lowest = FALSE,
            breaks = c(0, cumsum(rep(a4height, npages))))

groups <- split(seq_len(nrows), rows)

gl <- lapply(groups, function(id) tg[id,])

pdf("multipage.pdf", paper = "a4", width = 0, height = 0)
for(page in seq_len(npages)){
  grid.newpage()
  grid.rect(width=unit(21,"cm") - margin,
            height=unit(29.7,"cm")- margin)
  grid.draw(gl[[page]])
}
## alternative to explicit loop:
## print(marrangeGrob(grobs=gl, ncol=1, nrow=1, top=NULL))
dev.off()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ric*_*rta 2

pdf()有一个width和 一个height参数。

最好的选择是放大尺寸,然后如果您要打印到纸张上,那么您使用的任何程序都可能更适合。

或者,如果您想在一页上打印两列,只需迭代这些列即可:

# assuming `myDF` is your data.frame

pdf("filename.pdf")
for (cl in seq(from=1, to=ncol(myDF)-1, by=2)) {
      plot.new()
      grid.table(myDF[, cl+(0:1)])
    }
dev.off()
Run Code Online (Sandbox Code Playgroud)