2016-03-15 20 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()