Matplotlib Ref Contour
* * *
[ Matplotlib Reference Documentation](https://example.com/matplotlib/matplotlib-apiref.html)
`contour()` draws contour lines, `contourf()` draws filled contours.
Both are used to visualize 2D scalar fields (such as topographic 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 values (heights) at each grid point, shape same as X, Y |
| levels | int or array-like | Contour levels: integer means auto-generate N lines, array means specific level values |
| colors | color or list | Contour line colors (for contour) |
| cmap | str or Colormap | Color mapping (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 | Color handling for values beyond levels range: 'neither'/'both'/'min'/'max' |
| antialiased | bool | Anti-aliasing (for contourf), default True |
## clabel() Additional Notes
`clabel()` is used to add numeric 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 hill
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, spacing 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 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')
# terrain colormap for terrain map simulation
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("tutorial: terrain contour displayed")
* * *
## FAQ
### When to use contour vs contourf?
`contour()`: Suitable for viewing clear boundary lines, such as pressure isolines.
`contourf()`: Suitable for displaying continuously changing fields, such as temperature distribution.
Common practice is to overlay both: contourf for color fill, contour for boundary lines.
### Do X and Y have to be 2D?
No. If 1D arrays are passed as X and Y, matplotlib will automatically call `np.meshgrid(X, Y)` to generate a 2D grid. Z must match the shape after meshgrid.
[ Matplotlib Reference Documentation](https://example.com/matplotlib
YouTip