现在位置: 首页 > Matplotlib 教程 > 正文

Matplotlib contour() / contourf() 函数


Matplotlib 参考文档 Matplotlib 参考文档

contour() 绘制等高线(轮廓线),contourf() 绘制填充等高线。

两者用于可视化二维标量场(如地形图、温度场、压力场等)。

函数定义

pyplot 接口

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

Axes 接口

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

参数说明

参数类型说明
X, Y2D array-like 或 1D array网格点的 x 和 y 坐标。如果传入 1D 数组,通过 meshgrid 自动扩展
Z2D array-like每个网格点的函数值(高度),形状同 X, Y
levelsint 或 array-like等高线的层级:整数表示自动生成 N 条,数组表示具体的层级值
colorscolor 或 list等高线颜色(contour 用)
cmapstr 或 Colormap颜色映射(contourf 用),如 'viridis'、'terrain'
alphafloat透明度 0-1
linewidthsfloat 或 list线宽(contour 用)
linestylesstr 或 list线型(contour 用),如 'solid'、'dashed'
extendstr超出 levels 范围的颜色处理:'neither'/'both'/'min'/'max'
antialiasedbool是否抗锯齿(contourf),默认 True

clabel() 补充说明

clabel() 用于在等高线上添加数值标签。

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

使用示例

示例 1:基本等高线 + 填充等高线对比

实例

import matplotlib.pyplot as plt
import numpy as np

# 创建二维网格和函数值
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)  # 二维函数

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

# 左图:轮廓线(contour)
cs1 = ax1.contour(X, Y, Z, levels=10, cmap='viridis')
ax1.clabel(cs1, inline=True, fontsize=8)  # 添加标签
ax1.set_title('contour() - Line Contours')

# 右图:填充等高线(contourf)
cs2 = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
fig.colorbar(cs2, ax=ax2, label='Value')
# 叠加边界线
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()

示例 2:自定义 levels

实例

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)

# 高斯山丘
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')

# 自定义 levels:0.1 到 1.0,间距 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()

示例 3:地形图风格(terrain colormap)

实例

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)

# 模拟地形:两个山峰 + 一个山谷
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 模拟地形图
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("runoob: terrain contour displayed")

常见问题

contour 和 contourf 什么时候用哪个?

contour():适合看清晰的边界线,如气压等值线。

contourf():适合展示连续变化的场,如温度分布。

常见做法是两者叠加:contourf 填充颜色,contour 叠加边界线。

X,Y 必须是 2D 的吗?

不是。如果传入 1D 数组作为 X 和 Y,matplotlib 会自动调用 np.meshgrid(X, Y) 生成二维网格。Z 必须与 meshgrid 后的形状一致。


Matplotlib 参考文档 Matplotlib 参考文档