Home > database >  How to create several plots with different names at once (ggplot in a loop)
How to create several plots with different names at once (ggplot in a loop)

Time:03-11

I have several variables that I have to visualize, each in a different plot. I have more than 20 variables, and I want to have each plot stored as an element, so I can create the final figures only with the ones that are useful for me. That's why I thought creating plots in a loop would be the best option.

I need several kinds of plots, but for this example, I will use boxplots. I want to stick to ggplot because it will allow me to tweak my graphs easily later.

let's say this is my data

a<-(rnorm(100,35,1))           
b<-(rnorm(100,5,1))            
c<-(rnorm(100,40,1))
mydata<-data.frame(a,b,c)

I would like to have histograms for each variable named Figure 1, Figure 2, and Figure 3.

I'm trying this, but with little experience with loops, I don't know where I'm wrong.

variable_to_be_plotted<-c("a","b","c")
    for (i in 1:3) {
      paste("Figure",i)<-print(ggplot(data = mydata, aes( variable_to_be_plotted[i] ))  
                             geom_boxplot())
    }

Thank you for taking the time to help me!

ps: please don't mark it as duplicate since I've been stuck for around 4 days digging into other people answers without being able to reproduce the code for my case.

CodePudding user response:

You can save the plots in a list. Here is a for loop to do that.

library(ggplot2)

variable_to_be_plotted<-c("a","b","c")
list_plots <- vector('list', length(variable_to_be_plotted))

for (i in seq_along(list_plots)) {
  list_plots[[i]] <- ggplot(data = mydata, 
                        aes(.data[[variable_to_be_plotted[i]]]))   geom_boxplot()
}

Individual plots can be accessed via list_plots[[1]], list_plots[[2]] etc.

CodePudding user response:

You can make the plots using lapply(), name the list of plots, and then use list2env()

plots = lapply(mydata, function(x) ggplot(mydata, aes(x))   geom_boxplot()) 
names(plots) <- paste("Figure", 1:3)
list2env(plots, .GlobalEnv)       
  • Related