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.

Syntax

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.

Parameters

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

np.random.seed(21)
data = np.random.rand(25).reshape(5, 5)
plt.imshow(data)
plt.show()

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')
plt.show()

matplotlib.pyplot.imshow() with green color

grey color

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

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)#
plt.show()

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')#
plt.show()

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)#
plt.show()

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