r语言 - 如何使用for循环生成多个ggplot



我想知道是否有人可以帮助我得到这个代码返回多个图形。我希望每张图都标注为"plot_i";(plot_G1 plot_G2)。我在如何让我的函数返回这个损失。任何帮助将不胜感激!

library(lubridate)
library(tidyverse)
#Dummy Data Frame
DateTime <- c("1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00","1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00","1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00")
Step <- c("Condition1","Condition1","Condition1","Condition2","Condition2","Condition2","Condition3","Condition3","Condition3")
G1 <- runif(9)
G2 <- runif(9)
G3 <- runif(9)
G4 <- runif(9)
test_df <- data.frame(DateTime = DateTime, Step = Step, G1 = G1, G2 = G2, G3 = G3, G4 = G4)
test_df$DateTime.lub <- ymd_hm(test_df$DateTime)
test_df
#Want to create a function that will provide graphs for every G1, G2, G3 and G4 and return them! 
list <- colnames(test_df)
list <- list[-c(1,2,7)]
list
#test plot - works
ggplot(data = test_df, aes(x= DateTime.lub, y = G1))+
geom_line(aes(size = Step))
#Function does not return graph
for (i in list){
ggplot(data = test_df, aes(x= DateTime.lub, y = i))+
geom_line(aes(colour = Step))
}

试试这个:

library(ggplot2)
#Function does not return graph
for (i in list){
var <- sym(i)
print(ggplot(data = test_df, aes(x= DateTime.lub, y = !!var))+
geom_line(aes(colour = Step))+
ggtitle(paste0('plot_',i)))
}

如果您想导出图形,请参见下面的内容:

plot_list = list()
for (i in list) {
var <- sym(i)    
p = ggplot(test_df, aes(x=DateTime.lub, y=!!var)) +
geom_line(aes(colour=Step))
print(p)
plot_list[[i]] = p
}
setwd("~/WD")
for (i in list) {
file_name = paste("plot_", i, ".tiff", sep="")
tiff(file_name)
print(plot_list[[i]])
dev.off()
}

最新更新