user224340
user224340

Reputation: 29

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

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())
    }

Upvotes: 0

Views: 1370

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389235

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.

Upvotes: 3

langtang
langtang

Reputation: 24845

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)       

Upvotes: 1

Related Questions