听起来您可以在这里使用嵌套循环:为您创建的每个文件创建一个外部循环,为您创建的每个多面板图形创建一个内部循环。由于所有数据帧都存储在一维列表中,因此需要跟踪正在打印的列表的索引。
有一种方法可以做到这一点:
nrow <- 1
ncol <- 2
n_panels <- nrow * ncol
n_files <- length(df_lst) / n_panels
for (i in seq_len(n_files)) {
file <- paste0("file_", i, ".pdf")
pdf(file, height = 6, width = 12)
par(mar = c(3, 3, 1, 0), mfrow = c(nrow, ncol))
for (j in seq_len(n_panels)) {
idx <- (i - 1) * n_panels + j
barplot(df_lst[[idx]]$y)
}
legend("bottom", legend = "Bar", fill = "grey")
dev.off()
}
如果只需要一个包含多个页面的文件,只需移动
pdf()
在原始循环之外调用,并在
PDF()
:
pdf('my/directory/file_Name.pdf', height = 6, width = 12)
par(mar=c(3,3,1,0), mfrow=c(1,2))
for (i in 1:length(df_lst)) {
barplot(df_lst[[i]]$y)
}
dev.off()