4.5 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Clear All Plots in RStudio (With Example)

How to Clear All Plots in RStudio (With Example)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories