Understand matplotlib.pyplot.imshow(): Display Data as an Image – Matplotlib Tutorial

By | August 19, 2020

matplotlib.pyplot.imshow() can display data as an image file, we will use some examples to show you how to use this function correctly in this tutorial.


matplotlib.pyplot.imshow() is defined as:

matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=<deprecated parameter>, filternorm=1, filterrad=4.0, imlim=<deprecated parameter>, resample=None, url=None, \*, data=None, \*\*kwargs)

It can display data X as an image.


X: array-like or PIL image

The shape of X can be:

(M, N) : an image with scalar data. The values are mapped to colors using normalization and a colormap

(M, N, 3): an image with RGB values (0-1 float or 0-255 int)

(M, N, 4): an image with RGBA values (0-1 float or 0-255 int)

We should notice: the value of X will be clipped between 0-1.

cmap: the Colormap

We will some examples to show how to use this function.

#-*- coding: UTF-8 -*- 
import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(25).reshape(5, 5)

Run this code, you will get this image.

matplotlib.pyplot.imshow() example 1

Display image with color green or grey

green color

plt.imshow(data, cmap='Greens')

matplotlib.pyplot.imshow() with green color

grey color

plt.imshow(data, cmap='Greys')#

matplotlib.pyplot.imshow() with gray color

Use aspect

aspect can be {‘equal’, ‘auto’} or float. It can set the ratio of each axis

Here is an example.

plt.imshow(data, aspect= 0.5)#

The image is:

matplotlib.pyplot.imshow() with aspect

Use origin

It is {‘upper’, ‘lower’}. It determines the position of (0, 0). Default value is upper.

plt.imshow(data, origin = 'lower')#

The image is:

matplotlib.pyplot.imshow() with origin

Use vmin and vmax

vmin and vmax limit the value of X

plt.imshow(data, vmin = 0.4, vmax = 0.6)#

The image is:

matplotlib.pyplot.imshow() with vmin and vmax

We can find the values lower than 0.4 or larger than 0.6 will be displayed with the same color.

Use interpolation

interpolation parameter is difficult to understand, we can display the effect of image with different value.

matplotlib.pyplot.imshow() with interpolation

You can select a good value to show image.

Leave a Reply

Your email address will not be published. Required fields are marked *