Matplotlib - Quiver Plot
Matplotlib - Quiver Plot (Vector Fields)
Section titled “Matplotlib - Quiver Plot (Vector Fields)”A Quiver Plot is used to visualize vector fields. It displays arrows at specific points (x, y) in a 2D plane, where each arrow represents a vector with components (u, v). The direction and magnitude of the arrows indicate the direction and strength of the field at those points.
Quiver plots are commonly used in physics, engineering, and meteorology to visualize things like fluid flow, wind patterns, electric/magnetic fields, or gradient fields.
The ax.quiver() method is used to create these plots.
ax.quiver(X, Y, U, V, **kwargs)Key Parameters
Section titled “Key Parameters”The first four arguments define the vector field:
X,Y: 1D or 2D arrays specifying the x and y coordinates of the arrow starting locations. If 1D,meshgridis often used to create 2D grids.U,V: 1D or 2D arrays specifying the x and y components of the vectors at each (X, Y) location. Must have the same shape as X and Y (if X/Y are 2D).
Common optional keyword arguments (**kwargs) for customization:
| Parameter | Description |
|---|---|
C | 1D or 2D array. Used to map colors to the arrows based on magnitude or another scalar quantity, used with cmap. |
color | Single color or sequence of colors for the arrows. |
cmap | Colormap used if C is provided. |
scale | Float. Scales the length of the arrows. Larger scale means shorter arrows. If None, autoscaling is used. |
scale_units | Units used for scaling (‘width’, ‘height’, ‘dots’, ‘inches’, ‘x’, ‘y’, ‘xy’). Controls how scale relates arrow length to plot dimensions or data units. |
angles | Specifies how arrow angles are determined (‘uv’ [default] or ‘xy’). ‘uv’ uses the U, V components directly. ‘xy’ uses the angle of the line from (x,y) to (x+u, y+v). |
width | Float. Width of the arrow shafts in plot units. |
headwidth | Float. Width of the arrow head base in multiples of shaft width. |
headlength | Float. Length of the arrow head in multiples of shaft width. |
pivot | String (‘tail’, ‘mid’, ‘tip’). The part of the arrow anchored at the (X,Y) coordinate. |
Example: Plotting the gradient field of a 2D function.
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()This code first defines a 2D grid and a scalar function Z on that grid. It then calculates the gradient of Z using np.gradient to get the vector components U (dZ/dX) and V (dZ/dY). Finally, ax.quiver plots arrows at each grid point (X, Y) with components (U, V). We optionally color the arrows based on the magnitude of the gradient vector and add a color bar.