Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib imshow() Function

Matplotlib imshow() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

imshow() Used to display an image on the Axes or render a 2D array as a heatmap.

It is the most commonly used 2D data visualization function, supporting various interpolation, colormap, and scaling methods.

Function definition

pyplot interface

matplotlib.pyplot.imshow(X, cmap=None, norm=None, *, aspect=None,
    interpolation=None, alpha=None, vmin=None, vmax=None, origin=None,
    extent=None, filternorm=True, filterrad=4.0, resample=None,
    url=None, **kwargs)

Axes interface

Axes.imshow(X, cmap=None, norm=None, *, aspect=None,
    interpolation=None, alpha=None, vmin=None, vmax=None, origin=None,
    extent=None, filternorm=True, filterrad=4.0, resample=None,
    url=None, **kwargs)

Parameter Description

Parameters Type Description
X array-like or PIL Image Image data to display. A 2D array is shown as grayscale/pseudocolor, a 3D array (MxNx3 or MxNx4) is shown as an RGB/RGBA image
cmap str or Colormap Colormap, effective only for 2D data. Default 'viridis'
norm Normalize or str Data normalization method, such as 'linear', 'log', 'symlog'
aspect str or float Pixel aspect ratio: 'equal' (default, pixels are square), 'auto' (automatically fill the Axes), a number (custom ratio)
interpolation str Interpolation method: 'none'/'nearest' (no interpolation), 'bilinear', 'bicubic', 'antialiased' (default), etc.
alpha float or array-like Transparency, 0-1
vmin, vmax float Data range of the colormap
origin str Origin position: 'upper' (default, [0,0] at the upper left) or 'lower' ([0,0] at the lower left)
extent tuple (left,right,bottom,top) Data boundary coordinates, change the axis labels but not the data

origin='upper'(default) places the first row of the array at the top, consistent with image display conventions.origin='lower' places the first row at the bottom, consistent with the mathematical coordinate system convention.


Usage examples

Example 1: Displaying a 2D array (heatmap)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a 10x10 2D array

np.

random

.

seed

(

42

)

data

=

np.

random

.

rand

(

10

,

10

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

6

,

5

)

,

layout

=

'constrained'

)

Display as a heatmap

im

=

ax.

imshow

(

data

,

cmap

=

'viridis'

,

aspect

=

'auto'

)

Display the value in each cell

for

i

in

range

(

10

)

:

   

for

j

in

range

(

10

)

:

        color

=

'white'

if

data

[

i

,

j

]

>

;

0.5

else

'black'

        ax.

text

(

j

,

i

,

f

'{data[i,j]:.2f}'

,

ha

=

'center'

,

                va

=

'center'

,

color

=

color

,

fontsize

=

8

)

Add a color bar

fig.

colorbar

(

im

,

ax

=

ax

,

label

=

'Value'

,

shrink

=

0.8

)

ax.

set_title

(

'2D Array as Heatmap'

)

ax.

set_xlabel

(

'Column'

)

ax.

set_ylabel

(

'Row'

)

plt.

show

(

)

Example 2: The extent parameter controls the axes

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create 50x50 mathematical function data

x

=

np.

linspace

(

3

,

3

,

50

)

y

=

np.

linspace

(

3

,

3

,

50

)

X

,

Y

=

np.

meshgrid

(

x

,

y

)

Z

=

np.

sin

(

X

)

cos

(

Y

)

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

12

,

5

)

,

                                layout

=

'constrained'

)

Left: without extent, axis coordinates are pixel indices

im1

=

ax1.

imshow

(

Z

,

cmap

=

'RdYlBu'

,

origin

=

'lower'

)

ax1.

set_title

(

'Without extentn(pixel indices)'

)

fig.

colorbar

(

im1

,

ax

=

ax1

,

shrink

=

0.8

)

Right: with extent, axis coordinates are actual data coordinates

im2

=

ax2.

imshow

(

Z

,

cmap

=

'RdYlBu'

,

origin

=

'lower'

,

                 extent

=

[

3

,

3

,

3

,

3

]

)

 

[xmin, xmax, ymin, ymax]

ax2.

set_title

(

'With extentn(actual coordinates)'

)

ax2.

set_xlabel

(

'X'

)

ax2.

set_ylabel

(

'Y'

)

fig.

colorbar

(

im2

,

ax

=

ax2

,

shrink

=

0.8

)

plt.

show

(

)

Example 3: Comparing different interpolation methods

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a small-sized data (10x10) and enlarge it to show interpolation differences

data

=

np.

random

.

rand

(

10

,

10

)

interpolations

=

[

'none'

,

'nearest'

,

'bilinear'

,

'bicubic'

,

                 

'spline16'

,

'spline36'

,

'lanczos'

]

lanczos has been renamed - use 'lanczos' instead

fig

,

axes

=

plt.

subplots

(

2

,

3

,

figsize

=

(

12

,

8

)

,

                          layout

=

'constrained'

)

axes

=

axes.

flatten

(

)

for

ax

,

interp

in

zip

(

axes

,

interpolations

)

:

    im

=

ax.

imshow

(

data

,

cmap

=

'viridis'

,

interpolation

=

interp

)

    ax.

set_title

(

f

'interpolation="{interp}"'

)

    ax.

set_xticks

(

[

]

)

    ax.

set_yticks

(

[

]

)

Hide the last extra subplot

axes

[

1

]

.

set_visible

(

False

)

fig.

suptitle

(

'Comparison of Interpolation Methods'

,

fontsize

=

14

)

plt.

show

(

)

Example 4: Displaying a real image (RGB)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a 'gradient' image (simulating an RGB image)

Height 100, width 200, 3 color channels

height

,

width

=

100

,

200

image

=

np.

zeros

(

(

height

,

width

,

3

)

)

R channel: increases from left to right

image

[

:

,

:

,

0

]

=

np.

linspace

(

0

,

1

,

width

)

G channel: increases from bottom to top

image

[

:

,

:

,

1

]

=

np.

linspace

(

0

,

1

,

height

)

.

reshape

(

1

,

1

)

B channel: gradient along the diagonal

image

[

:

,

:

,

2

]

=

np.

sin

(

np.

linspace

(

0

,

4

*np.

pi

,

width

)

)

0.5

0.5

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

4

)

,

layout

=

'constrained'

)

A 3D array (M,N,3) is automatically recognized as an RGB image, no cmap needed

ax.

imshow

(

image

)

ax.

set_title

(

'Synthetic RGB Image'

)

ax.

set_xlabel

(

'Width (pixels)'

)

ax.

set_ylabel

(

'Height (pixels)'

)

plt.

show

(

)

print

(

"runoob: image displayed"

)

Example 5: Logarithmic normalization

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

from

matplotlib.

colors

import

LogNorm

Create data with a large range

x

=

np.

linspace

(

5

,

5

,

100

)

y

=

np.

linspace

(

5

,

5

,

100

)

X

,

Y

=

np.

meshgrid

(

x

,

y

)

Z

=

np.

exp

(

(

X**

2

2

)

/

2

)

1000

 

Gaussian function, values from 0 to 1000

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

12

,

5

)

,

                                layout

=

'constrained'

)

Left: linear normalization (default)

im1

=

ax1.

imshow

(

Z

,

cmap

=

'hot'

)

ax1.

set_title

(

'Linear Normalization'

)

fig.

colorbar

(

im1

,

ax

=

ax1

,

shrink

=

0.8

)

Right: logarithmic normalization (LogNorm)

im2

=

ax2.

imshow

(

Z

,

cmap

=

'hot'

,

norm

=

LogNorm

(

)

)

ax2.

set_title

(

'Log Normalization (LogNorm)'

)

fig.

colorbar

(

im2

,

ax

=

ax2

,

shrink

=

0.8

)

fig.

suptitle

(

'Linear vs Log Normalization'

,

fontsize

=

14

)

plt.

show

(

)


Common questions

The difference between origin='upper' and 'lower'?

origin='upper'(default): array [0, 0] at the upper left, y-axis from top to bottom, suitable for images.

origin='lower': array [0, 0] at the lower left, y-axis from bottom to top, suitable for mathematical/scientific data.

Can be done through plt.rcParams['image.origin'] = 'lower' to modify the default behavior globally.

imshow vs pcolormesh: how to choose?

imshow() Suitable for regular grids, large data volumes, fast rendering (rasterization-based).

pcolormesh() Suitable for irregular grids and when precise grid boundaries are needed (vector-based drawing).

How to display a grayscale image?

Settings cmap='gray' or cmap='Greys_r'(grayscale inversion).

Matplotlib Reference Documentation Matplotlib Reference Documentation