R assigning ggplot objects to list in loop

后端 未结 4 1733
梦谈多话
梦谈多话 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-06 23:53

    There is a nice explanation of what happens with ggplot2's lazy evaluation and for loops in [this answer](https://stackoverflow.com/a/26246791/2461552.

    I usually switch to aes_string or aes_ for situations like this so I can use variables as strings in ggplot2.

    I find lapply loops easier than a for loop in your case as initializing the list and using the counter can be avoided.

    First, I add the x variable to the dataset.

    dfrm$index = 1:nrow(dfrm)
    

    Now, the lapply loop, looping through the columns in v.

    myplots = lapply(v, function(x) {
        ggplot(dfrm, aes_string(x = "index", y = x)) + 
            geom_point() +
            labs(y = x)
    })
    
    plot_grid(plotlist = myplots)
    

提交回复
热议问题