Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using show() and close() from matplotlib

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?

like image 243
xarles Avatar asked Jul 13 '12 22:07

xarles


2 Answers

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.

like image 117
stanri Avatar answered Oct 17 '22 00:10

stanri


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().

like image 2
Matt Majic Avatar answered Oct 17 '22 01:10

Matt Majic