我有代码可以为循环的每次迭代在pdf的不同页面上生成和导出图。
当我在 Windows 7 中的 RGui 或 Rstudio 中运行它时,此代码按预期工作。 但是,当我尝试通过命令提示符使用 Windows 任务管理器或 Rscript 自动执行它时,我得到一个通用的、默认大小的 Rplot.pdf 输出,而不是 mtcars.pdf使用我在函数 pdf() 中分配的维度进行格式化。在这里,我使用 mtcars 来复制我的问题。 此代码按预期工作,并生成一个名为 mtcars 的 3 页 pdf,具有 7 x 5 的维度。
setwd("C:/")
library(ggplot2)
library(grid)
gear.cat <- unique(mtcars$gear)
plots <- vector(length(gear.cat), mode='list')
for (i in 1:length(gear.cat)) {
sub<- subset(mtcars , gear==gear.cat[i])
p1 <- ggplot(sub, aes(mpg, wt))+geom_point()
p2 <- ggplot(sub, aes(hp, cyl))+geom_point()
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last" ))
plots[[i]] <- recordPlot()
}
graphics.off()
pdf("mtcars.pdf", onefile=TRUE, width=7 ,height=5 )
for (each.plot in plots) {
replayPlot(each.plot)
}
graphics.off()
当我从cmd提示符运行相同的脚本时:
RScript C:mtcars.example.R
我得到一个pdf,其中有7 x 7的图,在3页上名为rplots.pdf,以及一个损坏的mtcars.pdf文件。
当我在单独的页面上导出 pdf 时,根据以下代码,它在 R 和 Rscript 中按预期工作。
setwd("C:/")
library(ggplot2)
library(grid)
gear.cat <- unique(mtcars$gear)
for (i in 1:length(gear.cat)) {
sub<- subset(mtcars , gear==gear.cat[i])
p1 <- ggplot(sub, aes(mpg, wt))+geom_point()
p2 <- ggplot(sub, aes(hp, cyl))+geom_point()
pdf(paste0("mtcarsb", gear.cat[i], ".pdf") , width=7 ,height=5 )
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last" ))
graphics.off()
}
任何允许我在 Rscript 中生成多页 pdf 图的建议将不胜感激。
pdf("xyz.pdf")
## All plots commands in between the above and below statement in the script.
dev.off()
希望这有帮助。
使用网格时,记录情节和重播情节似乎在 Rscript 中无法正常工作。 我改用了grid.grab,现在以下代码在R或Rscript中运行时提供了一致的结果。
setwd("C:/")
library(ggplot2)
library(grid)
library(gridExtra)
gear.cat <- unique(mtcars$gear)
plots <- vector(length(gear.cat), mode='list')
pdf("mtcarsddd.pdf", onefile=TRUE, width=7 ,height=5 )
for (i in 1:length(gear.cat)) {
sub<- subset(mtcars , gear==gear.cat[i])
p1 <- ggplot(sub, aes(mpg, wt))+geom_point()
p2 <- ggplot(sub, aes(hp, cyl))+geom_point()
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last" ))
plots[[i]]<- grid.grab()
}
dev.off()