2016-03-15 22 views
0

我有一个代码,用于生成循环的每次迭代并在pdf的单独页面上导出绘图。
当我在Windows 7的RGui或Rstudio中运行它时,此代码可以正常工作。但是,当我尝试通过命令提示符使用Windows任务管理器或Rscript自动执行它时,我得到一个通用的,默认大小的Rplot.pdf输出,而不是使用我在函数pdf()中分配的维度格式化mtcars.pdf。 在这里,我使用mtcars来复制我的问题。此代码按预期工作,并生成一个3页的pdf,命名为mtcars,尺寸为7乘5。PDF绘图在R与Rscript中的表现有所不同

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() 

当我运行从命令提示符同一个脚本:

RScript C:\mtcars.example.R 

我与图3页7×7地块命名rplots.pdf和腐败mtcars.pdf文件的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图将不胜感激。

回答

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

希望这会有所帮助。

+0

这并没有解决我为什么通过命令提示符运行R脚本的行为与在Rgui中运行不同的问题 – Wyldsoul

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()