Code to clear all plots in RStudio

RPlotRstudio

R Problem Overview


I have code to clear the workspace: rm(list=ls()) and code to clear the console: cat("\014")

Is there code to clear all plots from Rstudio?

R Solutions


Solution 1 - R

dev.off() closes the current graphical device. This clears all of the plots for me in RStudio as long as I don't have a different graphical device open at the moment. If you do have other graphical devices open then you can use dev.list() to figure out which graphical device is RStudio's. The following should do that but I haven't tested it thoroughly.

dev.off(dev.list()["RStudioGD"])

But if you aren't doing anything else then just using dev.off() should take care of it.

Solution 2 - R

dev.off() only works in an interactive session. If you're interested in implementing such behavior in a script, you should use

graphics.off()

instead.

Solution 3 - R

To prevent error message in case there are no plots to clear:

if(!is.null(dev.list())) dev.off()

Solution 4 - R

I usually use

while (dev.cur()>1) dev.off()

and since I use RGL a lot, I often add:

while (rgl.cur()) rgl.close()

Solution 5 - R

I have gone for this which seems to work without reporting any errors:

# Clear all plots
try(dev.off(dev.list()["RStudioGD"]),silent=TRUE)
try(dev.off(),silent=TRUE)

I merged the instructions from the other answers with an answer on error handling here:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondpelView Question on Stackoverflow
Solution 1 - RDasonView Answer on Stackoverflow
Solution 2 - RWaldir LeoncioView Answer on Stackoverflow
Solution 3 - RPatrícia GonçalvesView Answer on Stackoverflow
Solution 4 - RTomView Answer on Stackoverflow
Solution 5 - RMattGView Answer on Stackoverflow