首页 > 解决方案 > 将数据框保存为 pdf 调整宽度

问题描述

我发现它grid.table可用于将数据框绘制为 pdf 文件,如此所述。我想将数据框保存为横向 A4 格式,但是它似乎无法缩放数据,使其非常适合 pdf 的边界。

代码

library(gridExtra)

set.seed(1)
strings <- c('Wow this is nice', 'I need some coffee', 'Insert something here', 'No ideas left')
table <- as.data.frame(matrix(ncol = 9, nrow = 30, data = sample(strings,30, replace = TRUE)))
pdf("test.pdf", paper = 'a4r')
grid.table(table)
dev.off()

输出
不是整个表格都显示在 pdf 中: 在此处输入图像描述

问题
如何确保数据框被缩放以适合 A4 风景?我没有明确需要gridExtra或默认pdf保存,如果这些更容易解决,我可以使用任何其他包。


编辑

我遇到了另一个问题,显然可以计算出所需的高度和宽度tableGrob

tg = gridExtra::tableGrob(table)
h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
ggplot2::ggsave("test.pdf", tg, width=w, height=h, units = 'mm')

在这里h = 172.2w = 444.3它超过了标准 A4 的尺寸,即 210 x 279。所以我知道这会导致问题,但仍然无法缩小表格以适应 A4。

标签: rdataframepdfplotlandscape

解决方案


我想我可以将scale参数添加到ggsave. 我写了一个简单的函数来获得最佳比例:

optimal.scale <- function(w,h, wanted.w, wanted.h) max(c(w/wanted.w, h/wanted.h))

我在比例尺上添加了 0.1 以在绘图中添加边距,这样文本就不会直接位于纸的边缘。然后我将结果比例传递给ggsave

  tg = gridExtra::tableGrob(table
  h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
  w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
  scale = optimal.scale(w,h, 279, 210) + 0.1 #A4 = 279 x 210 in landscape 
  ggplot2::ggsave("test.pdf", tg, width = 279, height = 210, units = 'mm' , scale = scale)

现在我的桌子适合 A4:

在此处输入图像描述


推荐阅读