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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
When you are passing column name as a variable (like variable_to_be_plotted ) it is recommended to use .data. See this answer stackoverflow.com/questions/19826352/…
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)       

1 Comment

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"]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.