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

亡梦爱人 提交于 2020-03-17 10:21:01

问题


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.


回答1:


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

plt.close('all')

or you can terminate the associated Python process.




回答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.)




回答3:


As there seems no absolutely trivial solution to do this automatically from the script itself: the possibly simplest way to close all existing figures in pycharm is killing the corresponding processes (as jakevdp suggested in his comment):

Menu Run\Stop... (Ctrl-F2). You'll find the windows closed with a delay of few seconds.




回答4:


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



回答5:


On *nix you can use killall command.

killall app

closes every instance of window with app for the window name. You can also use the same command from inside your python script.
You can use os.system("bashcommand") to run the bashcommand.



来源:https://stackoverflow.com/questions/33853801/how-do-i-close-all-pyplot-windows-including-ones-from-previous-script-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!