How to close Matplotlib pyplot windows

In this tutorial we will explore how to close Matplotlib pyplot windows and figures programmatically. Uptil now the only method to close a Matplotlib window is to manually press the “close button” (located on the top-right corner). However there are various scenarios in which this is not sufficient, and we need to explore alternatives.

For example, if we face an error in our code, we may want to shut down the Matplotlib window. Or maybe you want to create a custom button which upon being clicked, will shut down the Matplotlib window.

This tutorial is actually more important than it looks, because sometimes even after we close the Matplotlib window (manually), the figure object still remains in memory. This eventually accumulates and slows down your program. And the only way of resolving this problem, is to properly shut down your Matplotlib Window using code.


How to close the pyplot Window

To close a pyplot window, all we have to do is call plt.close(). This function causes the current instance of the pyplot window to be closed.

Try running the below code where we have used the animation module, to call the plt.close() function after 2 seconds. You will notice that the Matplotlib window is created, and then destroyed after 2 seconds.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def input_func(frame):
    # Called after 2 seconds
    plt.close()

def init_animation():
    pass

f1 = plt.figure()
plt.plot([1, 2, 3])

animation = FuncAnimation(f1, input_func, interval = 2000, 
                         init_func= init_animation)
plt.show()

There are other parameters you can pass into the plt.close() function, depending on your requirements. If you have multiple plots open, and you want to remove the second one, you can do the following:

plt.close(2)

Keeping track of the plot “numbers” can be a little tricky, so if you want to close a particular plot all you have to do is pass its figure object in the plt.close() function, as shown below.

fig, ax = plt.subplots()
plt.close(fig)

If you want to close all plots (if you have multiple windows open), then you can do:

plt.close('all')

There is a slight chance that you might face memory issues even when you properly close your Windows.

This is a known issue, and one of the best (and easiest) ways of resolving it, is to change the way you create Matplotlib figures. Follow the link for more information about this problem and how to solve it.


This marks the end of the How to close Matplotlib pyplot windows Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments