r – Writing a fuction to Automate Repetitive Plotting in ggplot2

A great way to iterate over a list with a particular function would be to use lapply(). Here is an example that should demonstrate the concept.

library(ggplot2)

# data frames put into a list
d1 <- data.frame(x=1:10, y=1:10)
d2 <- data.frame(x=1:100, y=(1:100)^2)
d3 <- data.frame(x=1:200, y=log(1:200))

mylist <- list(d1, d2, d3)

# the custom function to be used for plotting
plot_function <- function(dat) {
  ggplot(dat, aes(x,y)) +
    geom_line(color="gray") + geom_point() +
    theme_bw()
}

myPlots <- lapply(mylist, plot_function)

This will store each plot as an element in a list of plots, myPlots. You can address each plot individually via myPlots[[1]], myPlots[[2]], and myPlots[[3]].

OP wanted to use this in ggarrange later, so it’s sufficient to stop here, although it might be useful to know you can further use lapply along the index of a list. This is useful for things like saving plots in a list, as you can see from the example below.

lapply(seq_along(myPlots),
  function(i) {
    ggsave(filename=paste0("plot",i,".png"), device = "png", plot = myPlots[[i]], width=6, height=3.5)
  }
)

This saves the plots as the following images.

enter image description here
enter image description here
enter image description here

Read more here: Source link