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

<span class="kwd">from</span><span class="pln"> matplotlib </span><span class="kwd">import</span><span class="pln"> pyplot </span><span class="kwd">as</span><span class="pln"> plt
fig </span><span class="pun">=</span><span class="pln"> plt</span><span class="pun">.</span><span class="pln">figure</span><span class="pun">()</span><span class="pln">
plt</span><span class="pun">.</span><span class="pln">figure</span><span class="pun">().</span><span class="pln">clear</span><span class="pun">()</span><span class="pln">
plt</span><span class="pun">.</span><span class="pln">close</span><span class="pun">()</span><span class="pln">
plt</span><span class="pun">.</span><span class="pln">cla</span><span class="pun">()</span><span class="pln">
plt</span><span class="pun">.</span><span class="pln">clf</span><span class="pun">()</span>

Output

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

Updated on: 2023-09-14T15:47:36+05:30

39K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements