Matplotlib contour() / contourf() Function
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
| Parameter | Type | Description |
|---|---|---|
| X, Y | 2D array-like or 1D array | x and y coordinates of grid points. If 1D arrays are passed, they are automatically expanded via meshgrid |
| Z | 2D array-like | Function value (height) at each grid point, same shape as X, Y |
| levels | int or array-like | Contour levels: an integer means automatically generate N levels, an array means specific level values |
| colors | color or list | Contour color (for contour) |
| cmap | str or Colormap | Colormap (for contourf), e.g., 'viridis', 'terrain' |
| alpha | float | Transparency 0-1 |
| linewidths | float or list | Line width (for contour) |
| linestyles | str or list | Line style (for contour), e.g., 'solid', 'dashed' |
| extend | str | Handling of colors outside the levels range: 'neither'/'both'/'min'/'max' |
| antialiased | bool | Whether 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()
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()
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")
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.
Other Extensions