You can use the following basic syntax to clear all plots in RStudio:
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 <- c(1, 1, 3, 4, 6, 7, 9, 10, 14, 19) y <- c(3, 5, 5, 4, 6, 9, 10, 14, 13, 14) z <- c(14, 14, 13, 10, 6, 9, 5, 4, 3, 5) #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.
The following tutorials explain how to perform other common tasks in R: