【问题标题】:How to generate multiple ggplots using a for loop [duplicate]如何使用 for 循环生成多个 ggplots [重复]
【发布时间】: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 &lt;- list() 之前和循环内 my_plots[[i]] &lt;- ggplot ...
  • 另外,您需要修改 y = i 以在循环内工作 - Duck 的回答提供了一个很好的例子。

标签: r ggplot2


【解决方案1】:

试试这个:

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)))
}

【讨论】:

  • @AngelaC 总是很高兴帮助你:)
【解决方案2】:

对于其他使用此功能的人,如果您想导出图表,请参见下文:

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()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    相关资源
    最近更新 更多