Saving multiple ggplots from ls into one and separate files in R

后端 未结 4 600
独厮守ぢ
独厮守ぢ 2020-12-01 00:08

I have several ggplots as objects on my ls. I want to save them as separate files (although I would also be interested to know how to save them all under 1 big file). I have

4条回答
  •  清歌不尽
    2020-12-01 01:02

    As an example fleshing out Joran's comment, and a supplement to Baptiste's answer, this is how you would initialize a list and store plots in a list up-front:

    plots <- list()
    plots[[1]] <- ggplot(...) # code for p1
    plots[[2]] <- ggplot(...) # code for p2
    
    ## Depending on if your plots are scriptable, you could use a loop
    
    for (i in 3:10) {
        plots[[i]] <- ggplot(...) # code for plot i
    }
    

    Then this list, plots, corresponds to l in baptiste's answer.

    When using lists, single brackets, [, are used for sublists, where you have to use double brackets [[ to get the element of a list. For example, plots[[1]] will give you the ggplot object that is the first element of plots, but plots[1] will give you a length one list containing that first plot as an element. This may seem confusing at first, but it makes sense, especially if you just wanted to plot the first three plots, then you could use myplots[1:3] instead of l in any of baptiste's examples. (See ?"[" for more details.)

    Whenever you catch yourself naming variables sequentially with numbers, e.g., x1, x2, x3, it's a good indication that you should be using a list instead.

提交回复
热议问题