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
.
plt. close() closes a window, which will be the current window, if not specified otherwise.
plt.figure ().close (): Close a figure window. close (name), where name is a string, closes the figure with that label Now, swap the statements "plt.show ()" and "plt.close ()" in the code. You wouldn't get to see any plot as the output because the plot would already have been closed.
How to Clear a Pyplot Figure. Figure is the top-level container object in a matplotlib plot. Figure includes everything visualized in a plot, including one or more Axes. You can use the matplotlib.pyplot.clf () function to clear the current Figure’s state.
On *nix you can use killall command. 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.
Only the second Axes is cleared with the cla () function: Figure 3. A Figure containing two Axes in different subplots. The first Axes is not cleared with the cla () function. The second Axes is cleared with cla (): Use ActiveState Python and accelerate your Python Data Science projects.
To close all open figures from a script, you can call
plt.close('all')
or you can terminate the associated Python process.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With