Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib plot and imshow

Tags:

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?

like image 745
user422100 Avatar asked Aug 16 '10 21:08

user422100


People also ask

What is CMAP in Imshow?

cmap : ~matplotlib.colors.Colormap , optional, default: None. If None, default to rc image.cmap value. cmap is ignored when X has RGB(A) information. However, if img were an array of shape (M,N) , then the cmap controls the colormap used to display the values.

What is Imshow used for?

imshow( I ) displays the grayscale image I in a figure. imshow uses the default display range for the image data type and optimizes figure, axes, and image object properties for image display.

How do you plot two images in python?

MatPlotLib with PythonAdd a subplot to the current figure, nrows=1, ncols=4 and at index=2. Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="Accent_r". Add a subplot to the current figure, nrows=1, ncols=4 and at index=3.


1 Answers

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 main loop 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 if 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 main loop will be run in a separate 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.

like image 186
Joe Kington Avatar answered Nov 15 '22 10:11

Joe Kington