【问题标题】:R::ggplot2 Loop over vector of Y to make multiple plots at one pageR::ggplot2 循环 Y 的向量以在一页上绘制多个图
【发布时间】:2020-07-08 17:05:02
【问题描述】:

我想在一页上创建多个图,我在同一个 X 上对不同的 Y 变量进行迭代。= 即我希望每个 Y 一个图。通常,我会复制并粘贴我的 ggplot更改 Y 值,将单个图存储为 p.y1, p.y2 并使用 grid.arrange(p.y1, p.y2) 绘制所有图,如下所示:

当我有 10 个不同的 Y 变量并且我想绘制所有这些变量时,这种方法不是很有趣。我想知道如何让这个过程更有效率?

我认为我可以简单地创建一个 Y 向量(df 的列名),然后遍历它们以创建多个图。但是,我的输出图似乎不正确传递给grid.arrange(),我也无法绘制它们。

如何循环遍历多个 Y,然后将所有绘图排列在一页上?由于我没有多重因素,我可能无法使用facet_gridfacet_wrap

这是我的两个 Y 的虚拟示例:y1 和 y2

set.seed(5)
df <- data.frame(x = rep(c(1:5), 2),
                 y1 = rnorm(10)*3+2,
                 y2 = rnorm(10),
                 group = rep(c("a", "b"), each = 5))  

# Example of simple line ggplot
ggplot(df, aes(x = x,
              y = y2,   # here I can set either y1, y2...
              group = group,
              color = group)) +
  geom_line()

现在,遍历 Ys 的向量并将输出图存储在列表中:

# create vector of my Ys
my.s<-c("y1", "y2")

# Loop over list of y to create different plots
outPlots<- list()

for (i in my.s) {
      print(i)
      my.plot <- 
        ggplot(df, aes_string(x = "x",
                              y = i,
                              group = "group",
                              color = "group")) +
        geom_line()
     # print(plot)
      outPlots <- append(outPlots, my.plot)
    }

在一页上绘制多个图表:由于Error in gList(list(data.x1 = 1L, data.x2 = 2L, data.x3 = 3L, data.x4 = 4L, : only 'grobs' allowed in "gList"而不起作用

grid.arrange(outPlots) 

【问题讨论】:

    标签: r ggplot2 plot


    【解决方案1】:

    我基于this post提出另一种解决方案。

    Plotfunction <- function(y){my.plot <- 
        ggplot(df, aes_string(x = "x",
                              y = y,
                              group = "group",
                              color = "group")) +
        geom_line()}
    
    n <- ceiling(sqrt(length(my.s)))
    do.call("grid.arrange",
            c(lapply(my.s, Plotfunction), ncol = n, nrow = n))
    

    【讨论】:

    • 谢谢@RemiCoulaud,这正是我想不通的。为了使其更加通用,我建议将ncol = 2 替换为ncol = length(my.s) 或类似的东西,以适应不同数量的Y。再次感谢!
    【解决方案2】:

    你可以试试这个。我希望这会有所帮助。

    library(reshape2)
    
    Melted <- melt(df,id.vars = c('x','group')) 
    
    #Plot
    ggplot(Melted,aes(x=x,y=value,group=group,color=group))+
      geom_line()+
      facet_wrap(~variable,ncol = 1,scales = 'free')+theme_bw()
    

    【讨论】:

    • 这是一个不错的方法,如果需要稍后添加另一个因素或修改ylim() 等,它会变得更加通用。谢谢@Duck!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多