Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting images side by side using matplotlib

I was wondering how I am able to plot images side by side using matplotlib for example something like this:

enter image description here

The closest I got is this:

enter image description here

This was produced by using this code:

f, axarr = plt.subplots(2,2) axarr[0,0] = plt.imshow(image_datas[0]) axarr[0,1] = plt.imshow(image_datas[1]) axarr[1,0] = plt.imshow(image_datas[2]) axarr[1,1] = plt.imshow(image_datas[3]) 

But I can't seem to get the other images to show. I'm thinking that there must be a better way to do this as I would imagine trying to manage the indexes would be a pain. I have looked through the documentation although I have a feeling I may be look at the wrong one. Would anyone be able to provide me with an example or point me in the right direction?

EDIT:

See the answer from @duhaime if you want a function to automatically determine the grid size.

like image 305
YellowPillow Avatar asked Jan 22 '17 17:01

YellowPillow


People also ask

How do I display photos side by side in matplotlib?

The easiest way to display multiple images in one figure is use figure(), add_subplot(), and imshow() methods of Matplotlib. The approach which is used to follow is first initiating fig object by calling fig=plt. figure() and then add an axes object to the fig by calling add_subplot() method.

How do I display multiple images in one figure correctly in matplotlib?

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


1 Answers

The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object.

The correct way of plotting image data to the different axes in axarr would be

f, axarr = plt.subplots(2,2) axarr[0,0].imshow(image_datas[0]) axarr[0,1].imshow(image_datas[1]) axarr[1,0].imshow(image_datas[2]) axarr[1,1].imshow(image_datas[3]) 

The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface. E.g. if ax is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..) instead of plt.plot(). This can actually be found exactly in the source from the page you link to.

like image 146
ImportanceOfBeingErnest Avatar answered Sep 25 '22 23:09

ImportanceOfBeingErnest