【问题标题】:Iterating over a list using ggarrange使用 ggarrange 遍历列表
【发布时间】:2020-09-07 06:14:54
【问题描述】:

我有以下代码,但不明白为什么 for 循环不起作用。我是新手,如果这很明显,请原谅,但它实际上并没有生成一组组合图(就像下面更暴力的方法所做的那样),它只是单独打印出每个图

library(ggpubr)
graphs <- lapply(names(hemi_split), function(i){ 
  ggplot(data=hemi_split[[i]], aes(x=type, y=shoot.mass))+
    geom_point()+
    facet_wrap(.~host, scales="free")+ 
    theme_minimal()+
    labs(title=i)
         });graphs

for (i in 1:length(graphs)) {
  ggarrange(graphs[[i]])
} ##not working 

## this works, and is the desired output
ggarrange(graphs[[1]], graphs[[2]], graphs[[3]],
          graphs[[4]], graphs[[5]], graphs[[6]],
          graphs[[7]], graphs[[8]], graphs[[9]],
          graphs[[10]], graphs[[11]])

谢谢!

【问题讨论】:

    标签: r loops ggplot2 ggpubr


    【解决方案1】:

    您可以使用do.call 提供graphs 的所有列表元素作为ggarrange 的参数:

    library(ggpubr)
    graphs <- lapply(names(mtcars)[2:5],function(x){
                    ggplot(mtcars,aes_string(x = x, y = "mpg")) +
                       geom_point()})
    do.call(ggarrange,graphs)
    

    【讨论】:

      【解决方案2】:

      使用purrr的另一种解决方案

      library(tidyverse)
      ggraphs <- map(names(mtcars)[2:5],
                  ~ ggplot(mtcars,aes_string(x = .x, y = "mpg")) +
                    geom_point())
      
      ggarrange(plotlist = ggraphs)
      

      【讨论】:

        猜你喜欢
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多