r - 将数据框保存为 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()
问题
如何确保数据框被缩放以适合 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.2
,w = 444.3
它超过了标准 A4 的尺寸,即 210 x 279。所以我知道这会导致问题,但仍然无法缩小表格以适应 A4。
解决方案
我想我可以将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:
推荐阅读
- hyperledger-fabric - 如何将身份分配给结构客户端实例?
- python - pymysql 中的 WHERE IN 子句返回最后一行
- ios - 使用 Vision 框架时在 Xcode 中获取控制台垃圾邮件并且面部移出屏幕
- reactjs - 使用 redux Provider 时反应导航出错
- reactjs - React ref 访问节点维度的当前值为 null
- vue.js - 如何在我的对象中添加计算数组?
- c# - c#, 获取当前T在List中的索引
- java - Java:根据参数类型调用不同方法的最有效方式,它们都共享相同的超类
- shell - 为 unqiue SRC + DST IP 排序日志文件
- c# - 打开邮件应用程序而不创建电子邮件草稿