0

I would like to know how to assign multiple plots generated by a function (e.g. a function from a loaded package) into either separate variables or as elements of a list/vector of sorts. Here is an example function that outputs three plots.

someFunction <- function(){
  plot(1:5, 1:5)
  plot(1:5, 5:1)
  plot(1:10, 1:10)
}

Using recordPlot() like this allows me to assign the last generated plot to a variable but I cannot find a way to capture the other two variables.

pdf(NULL)
dev.control(displaylist="enable")
someFunction()
a <- recordPlot()
invisible(dev.off())

Here I can print the last plot that I capture.

grid::grid.newpage()
a

I've been struggling with this problem for days now, so I would really appreciate any and all help I can get.

Thanks in advance :)

canul
  • 1
  • plot returns NULL i.e. `str( plot(1:5, 1:5)) NULL` you could change the `par` settings for display i.e. `par(mfrow = c(3, 1))` and then use `someFunction()` – akrun Sep 21 '21 at 00:05
  • Are you looking for base R option only using `plot` ? Are you open for using `ggplot2` library ? – Ronak Shah Sep 21 '21 at 05:58
  • 1
    @akrun Ideally, I would like to keep the plots separated from each other as distinct variables or elements of a list/vector, but if this is not possible, I think your solution is the next best thing – canul Sep 21 '21 at 08:27
  • @RonakShah Yes, I'm looking for the base R option of only using plot(). The function I give here is representative of a function loaded from a package that when run plots multiple plots using base R. – canul Sep 21 '21 at 08:36
  • @canul another option is to get the output directed to a pdf and then you won't have any issue – akrun Sep 21 '21 at 17:30
  • @akrun my aim is not to save the plots as pdf or png but rather to have them stored inside variables to call on them whenever possible in the code. – canul Sep 21 '21 at 19:39
  • @canul ok. unlike `ggplot`, `plot` objects return value is NULL and it just prints on the console – akrun Sep 21 '21 at 19:41
  • @canul in case you haven't looked at [this](https://stackoverflow.com/questions/29583849/save-a-plot-in-an-object) – akrun Sep 21 '21 at 19:52
  • @akrun yes thank you, these are functions that I tried and they work great for capturing a single base plot but cannot capture all three when they are printed on the console by the function. Everything would be much easier if the plotting was ggplot based but unfortunately it isn't. – canul Sep 22 '21 at 10:17
  • @akrun I think I will go with your `par(mfrow = c(3,1))` solution since at least it captures all three of the plots into one variable when used together with `recordPlot()`. – canul Sep 22 '21 at 10:18

0 Answers0