【问题标题】:renaming ggplot2 graphs in a for loop在 for 循环中重命名 ggplot2 图
【发布时间】:2011-05-28 11:33:03
【问题描述】:

我有一个关于在 for 循环中创建 ggplot2 图、根据迭代重命名它们然后在网格中排列图的问题。

我想做类似这个虚拟示例的事情

library(ggplot2)

a = c(1, 2, 3)

b = c(4, 5, 6)

for ( i in c(1:5)){

    x = i*a

    y = i*b

    p = qplot(x, y)

    ... do something to rename p as plot_i...

}

... 将plot_1 ... plot_6 的地块排列成 2 x 3 网格

有什么建议吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以将图保存到列表中:

    library(ggplot2) 
    library(gridExtra)
    
    a <- c(1, 2, 3) 
    b <- c(4, 5, 6)
    
    out <- NULL 
    for (i in 1:10){
        take <- data.frame(a = a * i, b = b * i)
        out[[i]] <- ggplot(take, aes(x = a, y = b)) + geom_point() 
    } 
    
    grid.arrange(out[[1]], out[[10]], out[[2]], out[[5]], nrow = 2)
    

    【讨论】:

      【解决方案2】:

      解决此问题的另一种方法是在情节中使用 use facets:

      a <- 1:3
      b <- 4:6
      
      # Create an empty data.frame
      pdata <- data.frame()
      for( i in 1:6){
        # Create a temporary data.frame to store data for single plot
        tmp <- data.frame(
            plot = i,
            x = i*a,
            y = i*b
        )
        # Use rbind to add this plot data
        pdata <- rbind(pdata, tmp)
      }
      
      # Plot results using ggplot with facets
      ggplot(pdata, aes(x=x, y=y)) + geom_point() + facet_wrap(~plot)
      

      【讨论】:

      • 感谢您的回复 - 它们正是我要找的东西
      【解决方案3】:

      cowplot 库有 plot_grid 函数可以很好地完成此操作:

      library(ggplot2)
      library(cowplot)
      
      makeplot <- function(i, a=c(1,2,3), b=c(4,5,6)) {
          take <- data.frame(a=a*i, b=b*i)
          ggplot(take, aes(x=a, y=b)) + geom_point()
      }
      
      nums = 1:10
      
      plots <- lapply(nums, makeplot)
      
      plot_grid(plotlist = plots)
      

      【讨论】:

        猜你喜欢
        • 2014-01-30
        • 1970-01-01
        • 2021-12-01
        • 2015-05-12
        • 2021-03-31
        • 2022-01-19
        • 1970-01-01
        • 2012-12-06
        • 2013-01-08
        相关资源
        最近更新 更多