【发布时间】:2021-04-26 00:58:44
【问题描述】:
我想知道是否有人可以帮助我获取此代码以返回多个图表。我希望每个图表都被标记为“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))
}
【问题讨论】:
-
你有一个
for循环,而不是一个函数。循环不返回任何内容。您可以显式地print()循环内的绘图以使其显示。如果要将绘图保留为 R 对象,则需要将它们分配在循环内,例如,在循环my_plots <- list()之前和循环内my_plots[[i]] <- ggplot ...。 -
另外,您需要修改
y = i以在循环内工作 - Duck 的回答提供了一个很好的例子。