How to clear the memory completely of all Matplotlib plots?


Using the following methods, we can clear the memory occupied by Matplotlib plots.

  • plt.figure() - Create a new figure or activate an existing figure.

  • plt.figure().close() -  Close a figure window.

    • close() by itself closes the current figure

    • close(h), where h is a Figure instance, closes that figure

    • close(num) closes the figure number, num

    • close(name), where name is a string, closes figure with that label

    • close('all') closes all the figure windows

  • plt.figure().clear() - It is the same as clf.

  • plt.cla() - Clear the current axes.

  • plt.clf() - Clear the current figure.

Example

from matplotlib import pyplot as plt
fig = plt.figure()
plt.figure().clear()
plt.close()
plt.cla()
plt.clf()

Output

When we execute the code, it will clear all the plots from the memory.

Updated on: 14-Sep-2023

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements