Saving multiple ggplot objects in a list/array/etc. from a for-loop, then printing/saving/etc. later

df = mtcars

cyls = unique(df$cyl)

for (c in cyls) {
  dff = df |>
    filter(cyl == c)
  
  gg_temp = dff |>
    ggplot() +
    geom_point(aes(y = mpg,
                   x = disp))
}

I would like to append multiple gg_temp object names into some list/array/vector. Then later, for example, outside of this for-loop, I would like to print the ggplots into the R Studio's viewer accompanied by Sys.sleep(3). I can figure out how to save the graph, but viewing is not working. How can I do this?

Here is an example of saving them as .tiff or .pdf (you can do .png or other formats too). Second example is typically the most standard which people use which makes use of ggsave


############################Example 1:

# 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()
#> png 
#>   2

############################Example 2: 

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")
}

Created on 2022-01-10 by the reprex package (v2.0.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.