Fabi Fabi - 29 days ago 8
R Question

R save plots with for loop (saving histograms works)

I want to save 300 plots with a for loop but somehow the code works in the console but no plots are saved. I always get the following error:

Error in plot_list[[i]] : subscript out of bounds


If I plot histograms everything works just fine.

Here's my code:

plot_list = list()
for (i in 1:300) {
p <-plot(matrix(1:15000, nrow = 15000, ncol = 50), datamatrix[1:15000,var_list[i,1]:var_list[i,2]], main = layer_list[[1]][i], xlab = "r [micrometer]")
plot_list[[i]] = p
}

for (i in 1:300) {
png(paste("plot", i, ".png", sep = ""), width = 1200, height = 750)
plot(plot_list[[i]], main = substitute(paste('Layer ', a), list(a=layer_list[[1]][i])), xlab = "r [micrometer]", ylab = " Frequency")
dev.off()
}


If I look at the plot_list, I get:


plot_list


list()


Can anyone help? Thank you!

Answer

Please try to provide datamatrix, or at least head(datamatrix).

As in the comments, you can do this is one loop and don't need to save objects to an intermediate list.

for (i in 1:300) {  
  png(paste("plot", i, ".png", sep = ""), width = 1200, height = 750)

  plot(matrix(1:15000, nrow = 15000, ncol = 50),
        datamatrix[1:15000, var_list[i, 1]:var_list[i, 2]],
        main = sprintf("Layer %s", layer_list[[1]][i]),
        xlab = "r [micrometer]",
        ylab = "Frequency")

 dev.off()
}