I'd like to create different figures in Python using matplotlib.pyplot
. I'd then like to save some of them to a file, while others should be shown on-screen using the show()
command.
However, show()
displays all created figures. I can avoid this by calling close()
after creating the plots which I don't want to show on-screen, like in the following code:
import matplotlib.pyplot as plt
y1 = [4, 2, 7, 3]
y2 = [-7, 0, -1, -3]
plt.figure()
plt.plot(y1)
plt.savefig('figure1.png')
plt.close()
plt.figure()
plt.plot(y2)
plt.show()
plt.close('all')
This saves the first figure and shows the second one. However, I get an error message:
can't invoke "event" command: application has been destroyed while executing
Is it possible to select in a more elegant way which figures to show?
Also, is the first figure()
command superfluous? It doesn't seem to make a different whether I give it or not.
Many thanks in advance.
Generally speaking, you can just close the figure. As a quick example:
As far as whether or not the first
plt.figure()
call is superflous, it depends on what you're doing. Usually, you want to hang on to the figure object it returns and work with that instead of using matplotlib's matlab-ish state machine interface.When you're making more complex plots, it often becomes worth the extra line of code to do something like this:
The advantage is that you don't have to worry about which figure or axis is "active", you just refer to a specific axis or figure object.
The better way is to use
plt.clf()
instead ofplt.close()
. Moreoverplt.figure()
creates a new graph while you can just clear previous one withplt.clf()
:This code will not generate errors or warnings such can't invoke "event" command...