Reputation: 974
I have spent over an hour searching, just to figure this simple thing. So, before considering this a duplicate question, please compare my question to any question out there.
This is my code:
import pandas
import matplotlib.pyplot as plt
dataset = pandas.read_csv('international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=1)
print dataset, type(dataset)
plt.plot(dataset)
plt.show()
plt.close()
Firstly, plt.show()
to my understanding is a blocking function. So what is the way to close the figure. There is no point in writing plt.close()
after it. So where is the right way to put it.
Secondly, how can I make sure all the windows are closed when I execute a new process of the same python code. For example in MATLAB, one could easily say close all in the beginning of their file and it closes all the opened plots which were the result of previous MATLAB code execution. plt.close('all')
is not working either.
I am using PyCharm. The results I found for the first situation, might work on IDLE but not in the PyCharm. How can I do it PyCharm.
Upvotes: 6
Views: 9765
Reputation: 1537
plt.show(block=False)
will do the trick- This is the way you can make this function non-blocking (both in run & debug mode). The main dis-advantage is that if the code ends, the figure is automatically closes...
Upvotes: 5
Reputation: 21
I had the same problem. I fix it making the python file in Pycharm to run in only one console. Go to: run---Edit configuration-- check that "single instance only" is activated
Upvotes: 2
Reputation: 10308
There are two ways to run matplotlib, non-interactive and interactive. In non-interactive mode, the default, you are right that plt.show()
is blocking. In this case, calling plt.close()
is pointless, the code won't stop as long as the figure is open. In interactive mode, however (which can be triggers by plt.ion()
), this code will open then immediately close the figure. You would need to put something to wait for user input if you run code like this in a script. Interactive mode, as the name implies, is designed more for running interactively rather than in a script.
As for closing figures from multiple runs of a python script, this isn't possible. If you open multiple instances of MATLAB, close all
in one instance won't close the figures in another instance. Running multiple processes of the same python code is the same as opening multiple instances of MATLAB, one run has no knowledge of the others.
Upvotes: 1