Home > Mobile >  Writing a fuction to Automate Repetitive Plotting in ggplot2
Writing a fuction to Automate Repetitive Plotting in ggplot2

Time:12-06

Hello I have a list (list1) that includes three dataframes. I would like to write a function to automate the task:

b<- ggplot(data = list1[[1]], mapping = aes(x = lag, y = acf))  
  geom_hline(aes(yintercept = 0))  
  geom_segment(mapping = aes(xend = lag, yend = 0))
b
c<- ggplot(data = list1[[2]], mapping = aes(x = lag, y = acf))  
  geom_hline(aes(yintercept = 0))  
  geom_segment(mapping = aes(xend = lag, yend = 0))
c

Any idea how to do that? I need to have the plots in order to use ggarrange later.

CodePudding user response:

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

  • Related