23

I've made different plots (more than a hundred) for a project and I haven't capture them on the way (yes it's bad , i know). Now, I need to save them all at once but without running again my script (which takes hours). Is there a way to do so within Rstudio ?

Edit: All the plot are already there and I don't want to run them again.

6
  • if you generated them already, you could just flip back in the Plots viewer and save
    – mtoto
    Feb 10, 2016 at 17:21
  • 1
    @mtoto, yes I already know that. But through hundred of plots , it will be fastiduous...
    – Aman Gast
    Feb 10, 2016 at 17:26
  • 1
    If you've created hundreds of plots it would seem that you created them programmatically, therefore you can save them by other methods
    – mlegge
    Feb 10, 2016 at 18:09
  • 1
    Not easily. You don't have much control over plots produced that way anyway; it's better to use a device or ggsave.
    – alistaire
    Feb 10, 2016 at 21:00
  • @GabrielFair: probably worth mentioning your system details, as I think windows(), .SavedPlots etc are OS dependent
    – user20650
    Dec 16, 2018 at 16:58

5 Answers 5

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

41
+50

In RStudio, every session has a temporary directory that can be obtained using tempdir(). Inside that temporary directory, there is another directory that always starts with "rs-graphics" and contains all the plots saved as ".png" files. Therefore, to get the list of ".png" files you can do the following:

plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE); 
plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE)

Now, you can copy these files to your desired directory, as follows:

file.copy(from=plots.png.paths, to="path_to_your_dir")



Additional feature:

As you will notice, the .png file names are automatically generated (e.g., 0078cb77-02f2-4a16-bf02-0c5c6d8cc8d8.png). So if you want to number the .png files according to their plotting order in RStudio, you may do so as follows:

plots.png.detials <- file.info(plots.png.paths)
plots.png.detials <- plots.png.detials[order(plots.png.detials$mtime),]
sorted.png.names <- gsub(plots.dir.path, "path_to_your_dir", row.names(plots.png.detials), fixed=TRUE)
numbered.png.names <- paste0("path_to_your_dir/", 1:length(sorted.png.names), ".png")

# Rename all the .png files as: 1.png, 2.png, 3.png, and so on.
file.rename(from=sorted.png.names, to=numbered.png.names)

Hope it helps.

7
  • 2
    great answer! your first block can be replaced by plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE); plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE) Dec 17, 2018 at 11:23
  • @Moody_Mudskipper, thanks for that. I have updated my answer to reflect your suggestion. Dec 17, 2018 at 11:32
  • 1
    Nice - platform independent (and actually works) unlike previous answers
    – dww
    Dec 17, 2018 at 17:25
  • 1
    Great! Just found out that the PNG is created just upon actually viewing in RStudio, i.e. in my script plots created during a loop did not show up in the folder as PNG until after using the back(/forward) button (i.e. actually viewing) in the R studio graphics window.
    – Martin
    May 5, 2019 at 14:40
  • Wouldn't it be best to change the temporary filenames with code right after the plotting before storing them this way? The reason to output a plot is often entertaining the option to save it.
    – user7182686
    Jun 2, 2019 at 14:38
5

Although this discussion has been inactive for a while, there are some persons, like myself, who still come across the same problem, and the other solutions don't really seem to even get what the actual question is.

So, hands on. Your plot history gets saved in a variable called .SavedPlots. You can either access it directly, assign it to another variable in code or do the latter from the plots window.

# ph for plot history
ph <- .SavedPlots

In R 3.4.2, I could index ph to reproduce the corresponding plot in a device. What follows is rather straightforward:

  1. Open a new device (png, jpeg, pdf...).
  2. Reproduce your plot ph[index_of_plot_in_history].
  3. Close the device (or keep plotting if it is a pdf with multiple pages).

Example:

for(i in 1:lastplot) {
    png('plotname.png')
    print(ph[i])
    dev.off()
}

Note: Sometimes this doesn't happen because of poor programming. For instance, I was using the MICE package to impute many datasets with a large number of variables, and plotting as shown in section 4.3 of this paper. Problem was, that only three variables per plot were displayed, and if I used a png device in my code, only the last plot of each dataset would be saved. However, if the plots were printed to a window, all the plots of each dataset would be recorded.

4
  • I got Error: object '.SavedPlots' not found, though .SavedPlots is referenced in ?grDevices::windows Dec 17, 2018 at 10:58
  • Could you provide more context to your problem?
    – Mr. Duhart
    Dec 19, 2018 at 10:57
  • 1
    If on a fresh session I run plot(1:10);.SavedPlots), I get the error mentioned above, so it doesn't seem like my plotting history is saved in this variable. Using R 3.3.1 on Windows. Dec 19, 2018 at 14:33
  • It looks like this only works if you've enabled recording plots before you started plotting. As far as I can see, you can do that manually when opening a window with windows(..., record=TRUE), or by setting windows.options(record=TRUE), possibly in a startup-script such as .Rprofile (and this needs to be run before a graphics device is opened, so more difficult in RStudio)
    – Emil Bode
    Dec 19, 2018 at 21:49
1

If your plots are 3d, you can take a snapshot of all your plots and save them as a .png file format.

snapshot3d(filename = '../Plots/SnapshotPlots.png', fmt = 'png')

Or else, the best way is to create a multi-paneled plotting window using the par(mfrow) function. Try the following

plotsPath = "../Plots/allPlots.pdf"
pdf(file=plotsPath)  

    for (x in seq(1,100))   
    {   
      par(mfrow = c(2,1))
      p1=rnorm(x)  
      p2=rnorm(x)  
      plot(p1,p2)   
    } 
    dev.off() 

You can also use png, bmp, tiff, and jpeg functions instead of pdf. You can read their advantages and disadvantages and choose the one you think is good for your needs.

0

I am not sure how Rstudio opens the device where the plot are drawn, but I guess it uses dev.new(). In that case one quick way to save all opened graphs is to loop through all the devices and write them using dev.print.

Something like :

lapply(dev.list(),function(d){dev.set(d);dev.print(pdf,file=file.path(folder,paste0("graph_",d,".pdf"))})

where folder is the path of the folder where you want to store your graph (could be for example folder="~" if you are in linux and want to store all your graph in your home folder).

2
  • 1
    I don't think this will work - I believe (though I stand to be corrected) that RStudio always writes to the device RStudioGD, replacing plots in the same device as it goes.
    – dww
    Dec 17, 2018 at 16:48
  • but in that case how is that possible that "All the plot are already there and I don't want to run them again" as says the authors? if they are drawn all in the same device you should see only one plot, as you say, Rstudio should be "replacing plots in the same device". I was assuming that the authors was using a kind of special function from Rstudio allowing him to plot each graph in a new window, something like that. But that's just a guess, the truth is I may be totally wrong.
    – Simon C.
    Dec 18, 2018 at 6:49
-2

If you enter the following function all that will follow will be save in a document:

pdf("nameofthedocument.pdf")

plot(x~y)
plot(...


dev.off()

You can also use tiff(), jpg()... see ?pdf

1
  • It is or it was in 2016. What's is not working for you ? Dec 17, 2018 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.