Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plot a vector field over the axes in Python Matplotlib?
A vector field displays vectors as arrows at different points in a coordinate system. In Python Matplotlib, we use the quiver() function to plot vector fields, where each arrow represents the direction and magnitude of vectors at specific coordinates.
Syntax
plt.quiver(X, Y, U, V, C, **kwargs)
Where:
X, Y − Grid coordinates for arrow positions
U, V − Vector components (arrow directions)
C − Optional array for color mapping
Example
Let's create a circular vector field using polar coordinates ?
import numpy as np import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create grid coordinates n = 8 X, Y = np.mgrid[0:n, 0:n] # Calculate polar coordinates from center T = np.arctan2(Y - n / 2., X - n / 2.) R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) # Calculate vector components U, V = R * np.cos(T), R * np.sin(T) # Create the plot plt.axes([0.025, 0.025, 0.95, 0.95]) plt.quiver(X, Y, U, V, R, cmap="copper") plt.show()
Output
How It Works
The vector field creation involves these key steps:
Grid Creation −
np.mgrid[0:n, 0:n]creates coordinate matricesPolar Conversion −
np.arctan2()calculates angles from centerVector Components −
U, Vrepresent x and y direction componentsColor Mapping −
Rvalues determine arrow colors via colormap
Key Parameters
| Parameter | Description | Effect |
|---|---|---|
cmap |
Color scheme | Controls arrow color mapping |
scale |
Arrow length scaling | Adjusts arrow sizes |
width |
Arrow shaft width | Changes arrow thickness |
Conclusion
The quiver() function effectively visualizes vector fields by plotting directional arrows. Use polar coordinates for circular patterns and adjust colormap parameters to enhance visual clarity of vector magnitudes and directions.
