Matplotlib - 向量场图
Matplotlib - 向量场图 (Quiver Plot)
Section titled “Matplotlib - 向量场图 (Quiver Plot)”向量场图 (Quiver Plot) 用于可视化向量场。它在二维平面上的特定点 (x, y) 处显示箭头,每个箭头代表一个具有分量 (u, v) 的向量。箭头的方向和大小表示在该点处场的方向和强度。
向量场图常用于物理、工程和气象学中,用于可视化流体流动、风场、电/磁场或梯度场等。
使用 ax.quiver() 方法创建这些图。
ax.quiver(X, Y, U, V, **kwargs)前四个参数定义向量场:
X,Y: 指定箭头起始位置的 x 和 y 坐标的一维或二维数组。如果是一维数组,通常使用meshgrid创建二维网格。U,V: 指定每个 (X, Y) 位置处向量的 x 和 y 分量的一维或二维数组。必须与 X 和 Y 具有相同的形状(如果 X/Y 是二维数组)。
常用的可选关键字参数(**kwargs)用于自定义:
| 参数 | 描述 |
|---|---|
C | 一维或二维数组。用于根据大小或其他标量值将颜色映射到箭头上,与 cmap 一起使用。 |
color | 箭头的单个颜色或颜色序列。 |
cmap | 如果提供了 C,则使用此颜色映射表。 |
scale | 浮点数。缩放箭头的长度。较大的 scale 值意味着较短的箭头。如果为 None,则使用自动缩放。 |
scale_units | 用于缩放的单位 (‘width’, ‘height’, ‘dots’, ‘inches’, ‘x’, ‘y’, ‘xy’)。控制 scale 如何将箭头长度与绘图尺寸或数据单位关联起来。 |
angles | 指定如何确定箭头的角度(‘uv’ [默认] 或 ‘xy’)。‘uv’ 直接使用 U、V 分量。‘xy’ 使用从 (x,y) 到 (x+u, y+v) 的连线的角度。 |
width | 浮点数。以绘图单位表示的箭头杆宽度。 |
headwidth | 浮点数。以箭头杆宽度的倍数表示的箭头头部底部的宽度。 |
headlength | 浮点数。以箭头杆宽度的倍数表示的箭头头部长度。 |
pivot | 字符串 (‘tail’ 尾部, ‘mid’ 中部, ‘tip’ 尖部)。锚定在 (X,Y) 坐标处的箭头部分。 |
示例:绘制二维函数的梯度场。
import matplotlib.pyplot as pltimport numpy as np
# 1. Define the gridx = np.arange(-3, 3.1, 0.4) # X coordinatesy = np.arange(-3, 3.1, 0.4) # Y coordinatesX, Y = np.meshgrid(x, y) # Create 2D grid
# 2. Define the scalar field (e.g., a function Z = f(X, Y))Z = X * np.exp(-X**2 - Y**2)
# 3. Calculate the vector components (e.g., gradient of Z)# np.gradient returns components corresponding to axes: (dZ/dY, dZ/dX)V, U = np.gradient(Z, 0.4, 0.4) # V = dZ/dY, U = dZ/dX (spacing is 0.4)
# --- Create the Quiver Plot ---fig, ax = plt.subplots(figsize=(7, 7))
# Optional: Display the underlying scalar field with contourf# contour = ax.contourf(X, Y, Z, levels=15, cmap='viridis', alpha=0.5)# fig.colorbar(contour, label='Z value')
# Plot the vectors using quiver# Color arrows by magnitude (optional)magnitude = np.sqrt(U**2 + V**2)quiver_plot = ax.quiver(X, Y, U, V, magnitude, # Color by magnitude cmap='plasma', # Colormap for coloring scale=15, # Adjust scale for arrow size pivot='mid' # Anchor arrows at their midpoint )
fig.colorbar(quiver_plot, label='Gradient Magnitude') # Colorbar for arrow colors
# --- Customize and Label ---ax.set_title('Quiver Plot of Gradient Field $\nabla Z$')ax.set_xlabel('X coordinate')ax.set_ylabel('Y coordinate')ax.set_aspect('equal', adjustable='box') # Make aspect ratio equal
plt.show()此代码首先定义了一个二维网格和一个在该网格上的标量函数 Z。然后使用 np.gradient 计算 Z 的梯度,以获得向量分量 U (dZ/dX) 和 V (dZ/dY)。最后,ax.quiver 在每个网格点 (X, Y) 处绘制带有分量 (U, V) 的箭头。我们选择根据梯度向量的大小为箭头着色,并添加一个颜色条(color bar)。