我发现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()
问题
如何确保将数据框缩放为适合横向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.2
和w = 444.3
超出了标准A4的大小,即210 x279。因此,我知道这会导致问题,但是仍然无法解决缩小表格的问题放在A4上
答案 0 :(得分:0)
我发现可以将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了: