组合来自 for 循环的 ggplot 对象

Combining ggplot objects from a for loop

我确实检查了这个问题,但找不到确切的解决方案。此外,应用该解决方案引发了另一个错误。

我确实写了下面的代理撮合功能

    library(tidyverse)
    library(cowplot)
    library(gridExtra)
    library(grid)
    library(Rmisc)


    matchmaking_two_value <- function(eta_lt,eta_rt,rho_lt,rho_rt,theta,time,
                                  target = c("eta_lt","eta_rt","rho_lt","rho_rt")){
  
    storage_v2 <- matrix(NA_real_, nrow = time, ncol = 4)
    graphs <- list()
    storage_v2 <- as.data.frame(storage_v2)
    colnames(storage_v2) <- c("eta_lt","eta_rt","rho_lt","rho_rt")
  
    for (i in 1:time) {
    storage_v2[i,1] <- eta_lt
    storage_v2[i,2] <- eta_rt
    storage_v2[i,3] <- rho_lt
    storage_v2[i,4] <- rho_rt
    
    
    eta_lt_next <- (2*eta_rt*rho_lt) - (2*eta_lt*rho_rt) + (2*theta*eta_lt*eta_rt) - (2*(1-theta)*eta_rt*eta_lt) + eta_lt^2
    eta_rt_next <- 1 - eta_lt_next - rho_lt - rho_rt
    
    if(eta_lt_next <= 0) {
      eta_lt <- 0
      eta_rt <- 1 - (eta_lt + rho_lt + rho_rt)
    } else{
      eta_lt <- eta_lt_next
      eta_rt <- eta_rt_next
    }
 
 
    
 
     }
         plot <- storage_v2%>%ggplot(mapping = aes(x = 1:time)) + 
         geom_line(aes(y = eta_lt, color = "Eta_L")) + 
         geom_line(aes(y = eta_rt, color = "Eta_R")) + 
         geom_line(aes(y = rho_lt, color = "Rho_L")) + 
         geom_line(aes(y = rho_rt, color = "Rho_R")) + 
         
         ggtitle("Population", subtitle = paste("Theta: ", theta)) + 
         ylab("Proportions") + xlab("Time") + 
         scale_color_manual(name = "Agent Types", 
                            breaks = c("Eta_L","Eta_R","Rho_L","Rho_R"), 
                            values = c("Eta_L" = "khaki4","Eta_R" = "salmon3", 
                                       "Rho_L" = "darkslateblue", "Rho_R" = "tomato4")) + 
         theme_minimal()
  
  
    print(storage_v2)
    print(plot)

}

如果我给出输入,这个函数就会给出结果。虽然我想用这个函数来创建多个图。比如下面

for(i in seq(0,0.9,0.1)){
matchmaking_two_value(eta_lt = i, eta_rt = 0.9-i, rho_lt= 0.05, rho_rt = 0.05, theta = 0.5, time = 10)
}

我的问题是我无法将函数的结果存储在列表下。任何解决方案将不胜感激

您需要一个实际上 return 具有值的函数。如果您只是 print() 函数中的结果,那么这些副作用将无法收集并在以后使用。所以改变你的功能从

matchmaking_two_value <- function(...){
  ...
  print(storage_v2)
  print(plot)
}

matchmaking_two_value <- function(...){
  ...
  list(data=storage_v2, plot=plot)`
}

然后当你是 return 列表时,你可以使用 lapply()

之类的东西快速收集列表中的这些值
result <- lapply(seq(0,0.9,0.1), function(i) {
  matchmaking_two_value(eta_lt = i, eta_rt = 0.9-i, rho_lt= 0.05, rho_rt = 0.05, theta = 0.5, time = 10)
})

然后您可以使用类似

的命令提取图表和数据
result[[1]]$plot
result[[1]]$data
result[[10]]$plot
result[[10]]$data

要获取要发送给 grid.extra 的所有地块的列表,您可以这样做

allplots <- lapply(result, function(x) x$plot)
gridExtra::grid.arrange(grobs=allplots)