I am experiencing some problems with matplotlib.... I can't open 2 windows at once to display a image with show(), it seems that the script stops at the line i use show and doesn't continue unless I close the display manually. Is there a way to close the figure window within the scrip?
the following code doesn't run as I want:
import matplotlib.pyplot as plt
from time import sleep
from scipy import eye
plt.imshow(eye(3))
plt.show()
sleep(1)
plt.close()
plt.imshow(eye(2))
plt.show()
I expected the first window to close after 1 second and then opening the second one, but the window doesn't close until I close it myself. Am I doing something wrong, or is it the way it is supposed to be?
plt.show() is a blocking function.
Essentially, if you want two windows to open at once, you need to create two figures, and then use plt.show() at the end to display them. In fact, a general rule of thumb is that you set up your plots, and plt.show() is the very last thing you do.
So in your case:
fig1 = plt.figure(figsize=plt.figaspect(0.75))
ax1 = fig1.add_subplot(1, 1, 1)
im1, = plt.imshow(eye(3))
fig2 = plt.figure(figsize=plt.figaspect(0.75))
ax2 = fig2.add_subplot(1, 1, 1)
im2, = plt.imshow(eye(2))
plt.show()
You can switch between the plots using axes(ax2)
.
I put together a comprehensive example demonstrating why the plot function is blocking and how it can be used in an answer to another question: https://stackoverflow.com/a/11141305/1427975.