R assigning ggplot objects to list in loop

后端 未结 4 1734
梦谈多话
梦谈多话 2020-12-06 23:41

I\'m using a for loop to assign ggplots to a list, which is then passed to plot_grid() (package cowplot). plot_grid

4条回答
  •  一个人的身影
    2020-12-07 00:10

    I believe the problem here is that the non-standard evaluation of the aes method delays evaluating i until the plot is actually plotted. By the time of plotting, i is the last value (in the toy example "B") and thus the y aesthetic mapping for all plots refers to that last value. Meanwhile, the labs call uses standard evaluation and so the labels correctly refer to each iteration of i in the loop.

    This can be fixed by simply using the standard evaluation version of the mapping function, aes_q:

    require(cowplot)
    
    dfrm <- data.frame(A=1:10, B=10:1)
    
    v <- c("A","B")
    dfmsize <- nrow(dfrm)
    myplots <- vector("list",2)
    
    count = 1
    for(i in v){
        myplots[[count]] <- ggplot(dfrm, aes_q(x=1:dfmsize, y=dfrm[,i])) + geom_point() + labs(y=i)
        count = count +1
    }
    plot_grid(plotlist=myplots)
    

提交回复
热议问题