How do I close all pyplot windows (including ones from previous script executions)?

56,893

Solution 1

To close all open figures from a script, you can call

plt.close('all')

or you can terminate the associated Python process.

Solution 2

import matplotlib.pyplot as plt
plt.close("all")

(In case you have pyplot already imported, you obviously don't need to import it again. In that case just make sure to replace plt in plt.close("all") with whatever alias you chose for pyplot when you imported it.)

Solution 3

This solution won't allow you to close plots from previous runs, but will prevent you from leaving them open!

The only way I have found to close these "hanging" figures is to find the process and kill.

Plot in a non blocking manner then ask for input. This should prevent you from forgetting to properly close the plot.

plt.show(block=False)
plt.pause(0.001) # Pause for interval seconds.
input("hit[enter] to end.")
plt.close('all') # all open plots are correctly closed after each run

Solution 4

I just had the same problem. I call a function that generates multiple plot windows. Each time I call the function the popped up plot windows accumulate in number. Trying matplotlib.pyplot.close('All') at the begining of the function didn't solve the problem. I solved the problem by calling matplotlib.pyplot.close(figure), where figure is a plot figure instance (object). I maintain a list of my plot figure objects. So, it is a good idea to maintain a list, and then call matplotlib.pyplot.close(figure) for each instance of a figure object:

import matplotlib.pyplot as plot

Add plot instance objects (figure,axis) to a list:

fig, (ax1,ax2) = plt.subplots(nrows=2)
figAxisDict = {'figure': fig, 'axis1': ax1, 'axis2':ax2}

figAxisList.append(figAxisDict)

Call the function for figure closing, and clear the list afterwards:

if len(figAxisList) !=0:

    for figAxis in figAxisList:
        figure=figAxis['figure']

        plot.close(figure)

    figAxisList[:]=[] 
Share:
56,893
Ron Ronson
Author by

Ron Ronson

Majoring in Mathematics in UCSF.

Updated on February 19, 2021

Comments

  • Ron Ronson
    Ron Ronson about 3 years

    So I have some python code that plots a few graphs using pyplot. Every time I run the script new plot windows are created that I have to close manually. How do I close all open pyplot windows at the start of the script? Ie. closing windows that were opened during previous executions of the script?

    In MatLab this can be done simply by using closeall.