R:使用for循环保存多个ggplots

时间:2014-09-25 08:44:38

标签: r for-loop ggplot2

我想自动生成一些ggplots:

通用数据集:

mydata<-data.frame(matrix(rnorm(100),ncol=5))
names(mydata)<-c("Tijd","X1","X2","X3","X4") 

指定要包含的变量:

Start=2
Stop=5

将图表保存在以下列表中:

gvec<-vector("list",length=length(Start:Stop))

创建图表:

for(i in Start:Stop){
  graphy<-ggplot(mydata,aes_string(x="Tijd",y=names(mydata)[i]))+geom_point()+mytheme
  gvec[[i-Start+1]]<-graphy
}

保存地块:

for(i in Start:Stop){
tiff(paste0("Test/Residu/Plots/Prei/mydata.",names(mydata)[i],"09.14.tiff"),width=720,height=720)
gvec[[i-Start+1]]
graphics.off()
}

生成图表列表;我也可以手动保存图表。但是,使用最后一个循环生成的文件都是空白的。我无法弄清楚这个的原因。

根据Roland的建议,我试过了 print(gvec[[i-Start+1]])但我仍然得到空白文件作为输出。

3 个答案:

答案 0 :(得分:53)

以下是在循环中创建ggplots的完全可重现的示例。

# Plot separate ggplot figures in a loop.
library(ggplot2)

# Make list of variable names to loop over.
var_list = combn(names(iris)[1:3], 2, simplify=FALSE)

# Make plots.
plot_list = list()
for (i in 1:3) {
    p = ggplot(iris, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
        geom_point(size=3, aes(colour=Species))
    plot_list[[i]] = p
}

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:3) {
    file_name = paste("iris_plot_", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
}

# Another option: create pdf where each page is a separate plot.
pdf("plots.pdf")
for (i in 1:3) {
    print(plot_list[[i]])
}
dev.off()

enter image description here

答案 1 :(得分:11)

您还可以使用ggsave库中的ggplot2功能。

library(ggplot2)
data("iris")

# list of values to loop over
  uniq_species = unique(iris$Species)


# Loop

for (i in uniq_species) {

  temp_plot = ggplot(data= subset(iris, Species == i)) + 
                  geom_point(size=3, aes(x=Petal.Length, y=Petal.Width )) +
                  ggtitle(i)

  ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}

答案 2 :(得分:1)

您可以在同一循环中创建和导出绘图。合并后的代码为:

for(i in Start:Stop){
  graphy<-ggplot(mydata,aes_string(x="Tijd",y=names(mydata)[i]))+geom_point()+mytheme
  tiff(paste0("Test/Residu/Plots/Prei/mydata.",names(mydata)[i],"09.14.tiff"),width=720,height=720)
  print(graphy)
  dev.off()  
}

对于堆叠数据的一般情况,id变量对应于子组(国家,个人等)):

for (i in 1:10) {
  mydata_id <- subset(mydata, id == i) # subselect group
  p <- ggplot(mydata_id, aes(x, y)) + geom_line() # create graph
  png(paste("plot_", i, ".png", sep = ""), width=600, height=500, res=120) # start export
  print(p) 
  dev.off() # finish export
}