When to use cla(), clf() or close() for clearing a plot in matplotlib?

cla() is used to clear the current axis of a plot in matplotlib. It is typically used when you want to reuse the same plot for multiple data sets and you want to clear the previous data from the plot before plotting the new data.

import matplotlib.pyplot as plt

# Create a new plot
plt.plot([1, 2, 3])

# Clear the current axis
plt.cla()

# Plot new data on the same axis
plt.plot([4, 5, 6])

Watch a course Python - The Practical Guide

clf() is used to clear the entire figure in matplotlib. It is typically used when you want to start a new plot from scratch and you want to clear any existing plots from the current figure.

import matplotlib.pyplot as plt

# Create a new plot
plt.plot([1, 2, 3])

# Clear the entire figure
plt.clf()

# Create a new plot
plt.plot([4, 5, 6])

close() is used to close a figure window. It is typically used when you are done with a plot and you want to close the figure window to free up memory or when you want to close all the open figure windows.

import matplotlib.pyplot as plt

# Create a new plot
plt.plot([1, 2, 3])

# Close the figure
plt.close()

It's important to keep in mind that the close() method will close the figure window, cla() will clear the current axis and clf() will clear the entire figure.