Home » How to Clear All Plots in RStudio (With Example)

How to Clear All Plots in RStudio (With Example)

by Erma Khan

You can use the following basic syntax to clear all plots in RStudio:

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

The following examples show how to use this syntax in practice.

Example 1: Clear All Plots in RStudio

Suppose we use the following code to create three different scatterplots in RStudio:

#create some vectors
x #create several scatterplots
plot(x, y)
plot(x, z)
plot(y, z)

We can view each of these scatterplots in the plotting window in RStudio:

We can use the blue arrows in the top left corner of the plotting window to scroll through the various plots we created.

We can then use the following code to clear all plots from the RStudio environment:

#clear all plots
dev.off(dev.list()["RStudioGD"]) 

The plotting window will now be cleared of all plots:

Example 2: Clear All Plots in RStudio (And Suppress Any Errors)

If there are no plots in RStudio and we attempt to clear all the plots, we will receive an error:

#attempt to clear all plots
dev.off(dev.list()["RStudioGD"])

Error in if (which == 1) stop("cannot shut down device 1 (the null device)") : 
  argument is of length zeroan>))

However, we can use a try() statement to suppress this error:

#attempt to clear all plots (suppress error if not plots exist)
try(dev.off(dev.list()["RStudioGD"]), silent=TRUE)

This code will attempt to clear all plots from RStudio and if no plots exist, no error will be shown.

When this code is run in the console window, we receive no error even though there are no plots to clear.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create an Empty Plot in R
How to Label Points on a Scatterplot in R
How to Create a Scatterplot in R with Multiple Variables

Related Posts