Articles - Tips & Tricks

How to Export Multiple ggplots Using a for Loop

  |   21281  |  Post a comment  |  Tips & Tricks  |  ggplot2, Tips & Tricks
To save multiple ggplots using for loop, you need to call the function print() explicitly to plot a ggplot to a device such as PDF, PNG, JPG file.

For example:



Code R :
 
library(ggplot2)
p <- ggplot(iris, aes(x = Species, y = Sepal.Length))
colors <- c("black", "red", "green")
 
for(color in colors){
 
   final.plot <- p + geom_boxplot(color = color)
 
  pdf(paste0(color, ".pdf"))
  print(final.plot)
  dev.off()
}