Matplotlib imshow() Function


Matplotlib 参考文档Matplotlib Reference Documentation

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

It is one of the most commonly used functions for 2D data visualization, supporting a variety of interpolation, colormapping, 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

ParameterTypeDescription
Xarray-like or PIL ImageThe image data to display. A 2D array is displayed as grayscale/pseudocolor, and a 3D array (MxNx3 or MxNx4) is displayed as an RGB/RGBA image.
cmapstr or ColormapColor mapping, only valid for 2D data. Default is 'viridis'.
normNormalize or strData normalization method, e.g., 'linear', 'log', 'symlog'.
aspectstr or floatPixel aspect ratio: 'equal' (default, square pixels), 'auto' (automatically fill the Axes), number (custom ratio).
interpolationstrInterpolation method: 'none'/'nearest' (no interpolation), 'bilinear', 'bicubic', 'antialiased' (default), etc.
alphafloat or array-likeTransparency, 0-1.
vmin, vmaxfloatData range of the colormap.
originstrOrigin position: 'upper' (default, [0,0] at the top-left corner) or 'lower' ([0,0] at the bottom-left corner).
extenttuple (left,right,bottom,top)Data boundary coordinates; changes 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 mathematical coordinate conventions.


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 values 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 colorbar
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) * np.cos(Y)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
                                layout='constrained')

# Left plot: 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 plot: 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: Comparison of Different Interpolation Methods

Example

import matplotlib.pyplot as plt
import numpy as np

# Create a small-sized dataset (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 redundant 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 direction
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("example: 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 + Y**2) / 2) * 1000  # Gaussian function, values from 0 to 1000

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
                                layout='constrained')

# Left plot: linear normalization (default)
im1 = ax1.imshow(Z, cmap='hot')
ax1.set_title('Linear Normalization')
fig.colorbar(im1, ax=ax1, shrink=0.8)

# Right plot: 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()

Frequently Asked Questions

What is the difference between origin='upper' and 'lower'?

origin='upper'(Default): Array [0, 0] is at the top-left corner, the y-axis goes from top to bottom, suitable for images.

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

Can be used toplt.rcParams['image.origin'] = 'lower'globally modify the default behavior.

How to choose between imshow and pcolormesh?

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

pcolormesh()Suitable for irregular grids and cases requiring precise grid boundaries (vector-based drawing).

How to display grayscale images?

Setcmap='gray'orcmap='Greys_r'(grayscale inversion).


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions