【问题标题】:Saving dataframe to pdf adjust width将数据框保存为 pdf 调整宽度
【发布时间】:2019-05-28 23:13:04
【问题描述】:

我发现grid.table 可用于将数据框绘制为 pdf 文件,如 here 所述。我想将数据框保存为横向 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 保存,如果这些更容易解决,我可以使用任何其他软件包。


编辑

我遇到了this other question,显然可以计算出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 .

【问题讨论】:

  • 您可以尝试在您的 pdf 声明中添加参数 width=9
  • @G5W 运行 pdf("test.pdf", paper = 'a4r', width = 9) 并没有改变输出(可能是因为 a4r 已经指定了输出 pdf 大小)

标签: r dataframe pdf plot landscape


【解决方案1】:

我发现我可以将scale 参数添加到ggsave。我写了一个简单的函数来获得最佳规模:

optimal.scale &lt;- 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:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2012-12-31
    相关资源
    最近更新 更多