How to Clear a Matplotlib Plot in Python?

Estimated read time 2 min read

In Matplotlib, you can clear a plot by calling the clf() method on the current figure object. The clf() method clears the current figure by removing all axes and plot elements from it.

Here’s an example of how to use the clf() method to clear a plot:

import matplotlib.pyplot as plt

# Create a simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)

# Clear the plot by calling the clf() method on the current figure
plt.clf()

# Show the empty plot
plt.show()

In this example, a simple line plot is created using the plot() function. The clf() method is then called to clear the plot, and finally, the empty plot is displayed using the show() function.

Alternatively, you can also use the close() method on the current figure to close the entire figure window and delete all the elements of the plot, like this:

import matplotlib.pyplot as plt

# Create a simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)

# Close the current figure and all its elements
plt.close()

# Show the empty plot
plt.show()

In this example, the close() method is called on the current figure to close and delete all the elements of the plot, effectively clearing the plot.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply