0

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())
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
user224340
  • 17
  • 6

2 Answers2

3

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you very much for your response Ronak, it works well for me :) When looking at how I should have done it, I understood the need of creating that list. However, I don't know how I would have reached to: ".data[[variable_to_be_plotted[i]]]". Could you please explain the logic behind it? – user224340 Mar 11 '22 at 02:14
  • 1
    When you are passing column name as a variable (like `variable_to_be_plotted` ) it is recommended to use `.data`. See this answer https://stackoverflow.com/questions/19826352/pass-character-strings-to-ggplot2-within-a-function – Ronak Shah Mar 11 '22 at 02:18
1

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)       
langtang
  • 22,248
  • 1
  • 12
  • 27
  • 1
    However, I'm not sure I would recommend naming your plot objects as "Figure 1", "FIgure 2", etc.. perhaps better to just leave them in the list (so drop the last line).. Then you can access them as you like, for, example: `plots[["Figure 1"]]` – langtang Mar 11 '22 at 01:31