Skip to content

Matplotlib - 等高线图

等高线图(Contour plots,或称为轮廓图,level plots)用于在二维平面上可视化三维表面。它们通过线条(等高线,contours)连接具有相同数值的点(例如,海拔、温度、压力),来显示三维函数 Z = f(X, Y) 的信息。填充等高线图则使用着色区域来表示等高线之间的 Z 值。

当您想了解响应变量 Z 如何随两个预测变量 X 和 Y 的变化而改变时,等高线图是非常理想的选择。

等高线图通常需要数据在一个规则网格上进行评估。numpy.meshgrid 函数对此至关重要。它接受 X 和 Y 坐标的数组,并创建表示网格中所有 X 和 Y 值组合的坐标矩阵。

import numpy as np
# Define the x and y coordinate vectors
# 定义 x 和 y 坐标向量
x_coords = np.linspace(-3.0, 3.0, 50)
y_coords = np.linspace(-3.0, 3.0, 50)
# Create the 2D grid
# 创建二维网格
X, Y = np.meshgrid(x_coords, y_coords)
# Define the function Z = f(X, Y)
# 定义函数 Z = f(X, Y)
# Example: Z represents distance from the origin
# 示例:Z 代表到原点的距离
Z = np.sqrt(X**2 + Y**2)

Matplotlib 在 Axes 对象中提供了两个主要的等高线图函数:

  • ax.contour(X, Y, Z, levels, ...): 绘制等高线。
  • ax.contourf(X, Y, Z, levels, ...): 创建填充等高线。

这两个函数都将网格坐标 X、Y 和相应的 Z 值作为主要输入。您可以选择指定等高线 levels(级别)的数量,或指定绘制等高线的具体数值。

import numpy as np
import matplotlib.pyplot as plt
# 1. Create data grid
# 1. 创建数据网格
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
# 2. Define function Z = f(X, Y) - Example: A wavy function
# 2. 定义函数 Z = f(X, Y) - 示例:一个波动函数
Z = np.sin(np.sqrt(X**2 + Y**2)) + np.cos(X * Y)
# 3. Create Figure and Axes
# 3. 创建 Figure 和 Axes 对象
fig, ax = plt.subplots(figsize=(7, 6))
# 4. Create the filled contour plot
# 4. 创建填充等高线图
# cmap specifies the colormap (e.g., 'viridis', 'plasma', 'coolwarm')
# cmap 指定色彩映射(例如 'viridis', 'plasma', 'coolwarm')
# levels can be an integer (number of levels) or a list of contour values
# levels 可以是一个整数(级别数量)或一个等高线值列表
cp = ax.contourf(X, Y, Z, levels=15, cmap='viridis')
# 5. Add contour lines for clarity (optional)
# 5. 添加等高线以增强清晰度(可选)
line_cp = ax.contour(X, Y, Z, levels=cp.levels, colors='black', linewidths=0.5)
# 6. Add a color bar to show the Z value scale
# 6. 添加颜色条以显示 Z 值比例尺
cbar = fig.colorbar(cp)
cbar.set_label('Z value')
# cbar.add_lines(line_cp) # Optionally add lines to colorbar
# cbar.add_lines(line_cp) # 可选:将等高线添加到颜色条中
# 7. Add labels and title
# 7. 添加标签和标题
ax.set_title('Filled Contour Plot Example')
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')
# 8. Ensure aspect ratio is equal if needed (optional)
# 8. 如有需要,确保宽高比相等(可选)
# ax.set_aspect('equal', adjustable='box')
plt.show()

此代码生成一个填充等高线图。它首先使用 meshgrid 创建一个二维网格,计算网格上每个点的 Z 值,然后使用 ax.contourf 绘制使用 ‘viridis’ 色彩映射的填充等高线。可选地使用 ax.contour 添加等高线,并包含一个颜色条来将颜色映射到 Z 值。标题和标签使图表易于理解。

  • levels: 控制等高线级别的数量和位置。
  • cmap: 指定 contourf 使用的色彩映射。
  • colors: 指定 contour 中线条的颜色。
  • linewidths: 指定 contour 中线条的粗细。