Using for loop in a list with charts in R

Asked

Viewed 107 times

2

This is my code:

library(ggplot2)
library(gridExtra)

df <- data.frame(x = 1:100,
                 y1 = runif(100),
                 y2 = runif(100)^2)

plot_list <- list(
  plot1 = ggplot(df, aes(x, y1)) + geom_point(),
  plot2 = ggplot(df, aes(x, y2)) + geom_point()
)

What I need is to access each Plot in this list using a for loop along with x11():

for (i in 1:length(plot_list)) {

  x11()

  plot_list[i]

}

Why doesn’t it work?

Some help?

Thank you!

Laura

  • 3

    Change plot_list[i] for print(plot_list[[i]]) or show(plot_list[[i]]). Ahhh and you’re in the stack in Portuguese, I think q got confused in the language of the post kkk

  • @Jorgemendes didn’t even notice!! kkkk I’ll do the translation kkk

  • @Jorgemendes thank you very much!!

2 answers

1

Jorge Mendes' answer is right, the code should be:

library(ggplot2)
library(gridExtra)

df <- data.frame(x = 1:100,
                 y1 = runif(100),
                 y2 = runif(100)^2)

plot_list <- list(
  plot1 <- ggplot(df, aes(x, y1)) + geom_point(),
  plot2 <- ggplot(df, aes(x, y2)) + geom_point()
)

for (i in 1:length(plot_list)) {

  x11()

  show(plot_list[[i]])

}

=)

0

In addition to Icarus Augustine’s response, you can use the apply family, which is more performative than the loop for:

library(ggplot2)
library(gridExtra)

df <- data.frame(x = 1:100,
                 y1 = runif(100),
                 y2 = runif(100)^2)

plot_list <- list(
  plot1 <- ggplot(df, aes(x, y1)) + geom_point(),
  plot2 <- ggplot(df, aes(x, y2)) + geom_point()
)

lapply(plot_list, function(x){
  x11()
  show(x)
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.