Matplotlib contour() / contourf() Function


Matplotlib 参考文档Matplotlib Reference Documentation

contour()Draw contour lines,contourf()Draw filled contours.

Both are used to visualize 2D scalar fields (such as terrain maps, temperature fields, pressure fields, etc.).

Function Definition

pyplot Interface

matplotlib.pyplot.contour(*args, **kwargs)
matplotlib.pyplot.contourf(*args, **kwargs)

Axes Interface

Axes.contour(X, Y, Z, levels=None, **kwargs)
Axes.contourf(X, Y, Z, levels=None, **kwargs)

Parameter Description

ParameterTypeDescription
X, Y2D array-like or 1D arrayx and y coordinates of grid points. If 1D arrays are passed, they are automatically expanded via meshgrid
Z2D array-likeFunction value (height) at each grid point, same shape as X, Y
levelsint or array-likeContour levels: an integer means automatically generate N levels, an array means specific level values
colorscolor or listContour color (for contour)
cmapstr or ColormapColormap (for contourf), e.g., 'viridis', 'terrain'
alphafloatTransparency 0-1
linewidthsfloat or listLine width (for contour)
linestylesstr or listLine style (for contour), e.g., 'solid', 'dashed'
extendstrHandling of colors outside the levels range: 'neither'/'both'/'min'/'max'
antialiasedboolWhether to enable anti-aliasing (for contourf), default True

clabel() Supplementary Notes

clabel()Used to add value labels on contour lines.

Axes.clabel(CS, levels=None, **kwargs)

Usage Examples

Example 1: Basic Contour + Filled Contour Comparison

Example

import matplotlib.pyplot as plt
import numpy as np

# Create 2D grid and function values
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)  # 2D function

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

# Left plot: contour lines (contour)
cs1 = ax1.contour(X, Y, Z, levels=10, cmap='viridis')
ax1.clabel(cs1, inline=True, fontsize=8)  # Add labels
ax1.set_title('contour() - Line Contours')

# Right plot: filled contours (contourf)
cs2 = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
fig.colorbar(cs2, ax=ax2, label='Value')
# Overlay boundary lines
ax2.contour(X, Y, Z, levels=15, colors='black', linewidths=0.3)
ax2.set_title('contourf() - Filled Contours')

for ax in [ax1, ax2]:
    ax.set_xlabel('X')
    ax.set_ylabel('Y')

plt.show()

Example 2: Custom Levels

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 150)
y = np.linspace(-5, 5, 150)
X, Y = np.meshgrid(x, y)

# Gaussian hills
Z = np.exp(-((X-1)**2 + Y**2) / 4) +
    np.exp(-((X+1)**2 + Y**2) / 3)

fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')

# Custom levels: 0.1 to 1.0, interval 0.1
custom_levels = np.arange(0.1, 1.1, 0.1)
cs = ax.contourf(X, Y, Z, levels=custom_levels,
                 cmap='YlOrRd', extend='both')
cbar = fig.colorbar(cs, ax=ax, label='Height')

ax.contour(X, Y, Z, levels=custom_levels,
           colors='black', linewidths=0.5)

ax.set_title('Custom Levels Contour')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

Example 3: Terrain Map Style (terrain colormap)

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-4, 4, 200)
y = np.linspace(-4, 4, 200)
X, Y = np.meshgrid(x, y)

# Simulate terrain: two peaks + one valley
Z = 3 * np.exp(-((X+2)**2 + Y**2) / 3) +
    2 * np.exp(-((X-1)**2 + (Y-1)**2) / 2) -
    1 * np.exp(-((X+0.5)**2 + (Y-2)**2) / 1.5)

fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')

# Use terrain colormap to simulate a terrain map
cs = ax.contourf(X, Y, Z, levels=20, cmap='terrain', extend='both')
fig.colorbar(cs, ax=ax, label='Elevation', shrink=0.8)

ax.contour(X, Y, Z, levels=20, colors='black', linewidths=0.3,
           alpha=0.4)

ax.set_title('Terrain-style Contour Map')
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.show()
print("example: terrain contour displayed")

Frequently Asked Questions

When to use contour vs contourf?

contour()contour: suitable for viewing clear boundary lines, such as isobars.

contourf()contourf: suitable for displaying continuously varying fields, such as temperature distribution.

A common practice is to overlay both: contourf fills colors and contour overlays boundary lines.

Must X, Y be 2D?

No. If 1D arrays are passed as X and Y, matplotlib will automatically callnp.meshgrid(X, Y)meshgrid to generate a 2D grid. Z must match the shape after meshgrid.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions