在R与Rscript

时间:2016-03-15 14:38:33

标签: r pdf plot cmd rscript

我有代码在循环的每次迭代中生成并导出pdf的不同页面上的绘图 当我在Windows 7中的RGui或Rstudio中运行它时,此代码按预期工作。但是,当我尝试使用Windows任务管理器或Rscript通过命令提示符自动执行它时,我得到一个通用的,默认大小的Rplot.pdf输出,而不是使用我在函数pdf()中指定的维度格式化的mtcars.pdf。 在这里,我使用mtcars来复制我的问题。此代码按预期工作,并生成一个名为mtcars的3页pdf,其中包含7×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 

我在一个名为rplots.pdf的3页上获得了一个带有7 x 7图的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图的建议都将非常感激。

2 个答案:

答案 0 :(得分:1)

   pdf("xyz.pdf")
   ## All plots commands in between the above and below statement in the script.
   dev.off()

希望这有帮助。

答案 1 :(得分:0)

使用网格时,似乎recordPlot和replayplot在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()