views:

54

answers:

1

The behavior of matplotlib's plot and imshow is confusing to me.

import matplotlib as mpl
import matplotlib.pyplot as plt

If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figure that gets opened, and then call plt.imshow(i), a new figure is displayed without ever calling plt.show().

Can someone explain this?

+3  A: 

If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly.

plt.show() displays the figure (and enters the mainloop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed.

plt.imshow() draws an image on the current figure (creating a figure is there isn't a current figure). Calling plt.show() before you've drawn anything doesn't make any sense. If you want to explictly create a new figure, use plt.figure().

...a new figure is displayed without ever calling plt.show().

That wouldn't happen unless you're running the code in something similar to ipython's pylab mode, where the gui backend's mainloop will be run in a seperate thread...

Generally speaking, plt.show() will be the last line of your script. (Or will be called whenever you want to stop and visualize the plot you've made, at any rate.)

Hopefully that makes some more sense.

Joe Kington