Search code examples
rfor-loopggplot2foreachpatchwork

Putting together a patchwork of plots by creating single plots by iterating over a for loop


I want to write a for loop that produces a grid of plots (like when using patchwork). I want to run the loop for each item in the color_list dataframe and use it as an aesthetic.

I managed to write the loop but am unsure how to retain all the plots and put them together at the end.

color_list <- data.frame(color = c("red", "blue", "green", "yellow"))

for(row in 1:nrow(color_list)) {
  data %>%
    ggplot(aes(x=x,y=y, color = color_list[row,]$color)) +
    geom_line()
}

Solution

  • You can create list of plots and pass it to any of the plotting library that you are using. For example, with patchwork::wrap_plots you can do :

    do.call(patchwork::wrap_plots, lapply(color_list$color, function(x) {
      ggplot(data, aes(x=x,y=y)) +geom_line(color = x)
    })) -> plot
    
    plot
    

    enter image description here

    data

    color_list <- data.frame(color = c("red", "blue", "green", "yellow"))
    data <- data.frame(x = rnorm(5), y = rnorm(5))