To plot a vector field in matplotlib, a simple solution is to use quiver:
quiver(X, Y, U, V, **kw)
with
- X : The x coordinates of the arrow locations
- Y : The y coordinates of the arrow locations
- U : The x components of the arrow vectors
- V : The y components of the arrow vectors
Plot a simple vector with quiver:
import matplotlib.pyplot as plt
import numpy as np
X = np.array((0))
Y= np.array((0))
U = np.array((2))
V = np.array((-2))
fig, ax = plt.subplots()
q = ax.quiver(X, Y, U, V,units='xy' ,scale=1)
plt.grid()
ax.set_aspect('equal')
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.title('How to plot a vector in matplotlib ?',fontsize=10)
plt.savefig('how_to_plot_a_vector_in_matplotlib_fig3.png', bbox_inches='tight')
#plt.show()
plt.close()
Plot a simple vector field with quiver
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.meshgrid(np.arange(-10, 10, 1), np.arange(-10, 10, 1))
x_shape = X.shape
U = np.zeros(x_shape)
V = np.zeros(x_shape)
for i in range(x_shape[0]):
for j in range(x_shape[1]):
U[i,j] = 1.0
V[i,j] = 1.0
fig, ax = plt.subplots()
q = ax.quiver(X, Y, U, V, units='xy' ,scale=2, color='red')
ax.set_aspect('equal')
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.title('How to plot a vector field using matplotlib ?',fontsize=10)
plt.savefig('how_to_plot_a_vector_field_in_matplotlib_fig1.png', bbox_inches='tight')
#plt.show()
plt.close()
References
Links | Site |
---|---|
matplotlib.pyplot.quiver | matplotlib doc |
pylab_examples example code: quiver_demo.py | matplotlib doc |
Plotting a vector field: quiver | scipy-lectures.org |
Vector field | wikipedia |
How can I set the aspect ratio in matplotlib? | stackoverflow |