11

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
xarles
  • 87
  • 1
  • 2
  • 12
  • Possible duplicate. Check http://stackoverflow.com/q/9753885/302369 – imsc Jul 13 '12 at 22:21
  • indeed that solves this problem, but I get another one..... when I use plt.ion() I cant use some resources such as zoom in the figure window(i can't even move the window around)... – xarles Jul 14 '12 at 04:07

2 Answers2

12

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.

Community
  • 1
  • 1
stanri
  • 2,922
  • 3
  • 25
  • 43
  • thanks, sir. But in my script, I'm trying to demonstrate like 100 plots one by one. I probably would not choose to plt.show() them all in the end. I want to show one plot, paused for maybe 1 second, then close it automatically in the scripts instead of close it manually, then repeatedly show the next one, for 100 times.Is there anyway to do this? Edit: I tried the plt.ion() on top of everything. Yes, the plots show up and get closed one by one. However, nothing appears on the figure window, all white. – StayFoolish May 14 '17 at 13:49
2

I use PyScripter and Python 2.7 and also had the problem of plt.show() blocking all executions until you manually close the figures.

I found that changing the Python engine to 'remote (Wx)' lets the script run after plt.show() - so could close figures with plt.close().

Matt Majic
  • 381
  • 9
  • 18