问题描述
尊敬的StackOverflow社区,
Dear StackOverflow Community,
多年来,我一直在社区中寻求帮助.感谢那.现在我自己有一个问题:
For years I have been finding help in the community. Thanks for that. Now I have a question on my own:
我正在尝试使用for循环在列表中存储多个ggplot图.该代码运行时没有错误,但是只打印了最后一张图表中的数据.
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)
}
现在,如果我运行该代码,则仅打印 last ggplot命令中的aes.因此,每个图形都使用不同的y轴打印,但是数据保持不变.
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.
我知道它与ggplot和aes有关,但我只是不知道问题出在哪里.我搜索了整个StackOverflow,其他建议(打印,dev.new等)没有帮助.
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
推荐答案
您可以执行以下操作:
library(ggplot2)
vars <- c("mpg", "wt", "qsec")
plots <- list()
for (var in vars) {
plots[[var]] <- ggplot(data=mtcars, aes_string(x=var)) + geom_histogram()
}
然后 l
将是一个包含3个 ggplot
的列表.如果要显示它们,可以执行以下操作:
Then l
would be a list with 3 ggplot
. If you want to display them, you can just do :
plots
这篇关于处理ggplot2和for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!