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

Pin*_*oes 35 for-loop r ggplot2

我想自动生成一些ggplots:

通用数据集:

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

指定要包含的变量:

Start=2
Stop=5
Run Code Online (Sandbox Code Playgroud)

列表保存图:

gvec<-vector("list",length=length(Start:Stop))
Run Code Online (Sandbox Code Playgroud)

创建图:

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

保存地块:

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()
}
Run Code Online (Sandbox Code Playgroud)

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

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

bde*_*est 69

这是一个在循环中创建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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


raf*_*ira 17

您也可以使用库中的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")
}
Run Code Online (Sandbox Code Playgroud)


luc*_*cho 6

您可以在同一循环中创建和导出绘图。组合代码将是:

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()  
}
Run Code Online (Sandbox Code Playgroud)

对于具有堆叠数据的一般情况,其中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
}
Run Code Online (Sandbox Code Playgroud)