Dealing with ggplot2 and a for loop

2019-09-10 07:49发布

问题:

Dear StackOverflow Community,

For years I have been finding help in the community. Thanks for that. Now I have a question on my own:

I am trying to store multiple ggplot graphs in a list with a for loop. The code runs without an error, but only the data from the last graph are printed.

# Preparation
metr_var <- c("schneehoehe",
              "wind_richtung",
              "wind_vmittel",
              "wind_vmax",
              "temp",
              "luftfeuchtigkeit"
             )
# Generating List
plot_list <- list()

# For Loop
for (j in metr_var) {
     p = ggplot(data = NULL, aes_string(x = arfang$arfang, y = arfang[, j])) 
     + geom_boxplot() + ylab(j) + theme_bw()
     dev.new()
     plot_list[[which(metr_var == j)]] = print(p)
}

Now, if I run that code, only the aes from the last ggplot command is printed. So each graph is printed with a different y-axis, but the data stays the same.

I know it has something to do with the ggplot and aes, but I just ca't figure out what the problem is. I have searched the entire StackOverflow and the other suggestions (print, dev.new, etc.) did not help.

Thanks for anyone helping me. Stan

回答1:

You can do something like this :

library(ggplot2)

vars <- c("mpg", "wt", "qsec")
plots <- list()

for (var in vars) {
  plots[[var]] <- ggplot(data=mtcars, aes_string(x=var)) + geom_histogram()
}

Then l would be a list with 3 ggplot. If you want to display them, you can just do :

plots


标签: r loops ggplot2