将数据框保存为 pdf 调整宽度
Saving dataframe to pdf adjust width
我发现 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 中并未显示整个 table:
问题
我如何确保数据框缩放以适合横向 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 x 279。所以我知道这会导致问题,但仍然无法缩小 table 把它装在 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)
现在我的 table 适合 A4:
我发现 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 中并未显示整个 table:
问题
我如何确保数据框缩放以适合横向 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 x 279。所以我知道这会导致问题,但仍然无法缩小 table 把它装在 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)
现在我的 table 适合 A4: