Pour tracer un simple vecteur avec matplotlib on peut utiliser arrow
Tracer un simple vecteur avec matplotlib

import matplotlib.pyplot as pltimport numpy as npax = plt.axes()ax.arrow(2.0, 4.0, 6.0, 4.0, head_width=0.5, head_length=0.7, fc='lightblue', ec='black')plt.grid()plt.xlim(0,10)plt.ylim(0,10)plt.title('How to plot a vector in matplotlib ?',fontsize=10)plt.savefig('how_to_plot_a_vector_in_matplotlib_fig1.png', bbox_inches='tight')#plt.show()plt.close()
Tracer un vecteur entre deux points
Un exemple de comment tracer un vecteur entre deux points A et B avec matplotlib en prenant en compte la
longueur de la tête (head_length).

import matplotlib.pyplot as pltimport numpy as npimport matha = [2.0,4.0]b = [8.0,8.0]head_length = 0.7dx = b[0] - a[0]dy = b[1] - a[1]vec_ab = [dx,dy]vec_ab_magnitude = math.sqrt(dx**2+dy**2)dx = dx / vec_ab_magnitudedy = dy / vec_ab_magnitudevec_ab_magnitude = vec_ab_magnitude - head_lengthax = plt.axes()ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=0.5, head_length=0.7, fc='lightblue', ec='black')plt.scatter(a[0],a[1],color='black')plt.scatter(b[0],b[1],color='black')ax.annotate('A', (a[0]-0.4,a[1]),fontsize=14)ax.annotate('B', (b[0]+0.3,b[1]),fontsize=14)plt.grid()plt.xlim(0,10)plt.ylim(0,10)plt.title('How to plot a vector in matplotlib ?',fontsize=10)plt.savefig('how_to_plot_a_vector_in_matplotlib_fig2.png', bbox_inches='tight')#plt.show()plt.close()
Tracer un vecteur avec quiver
Il est aussi possible de tracer un simple vecteur avec quiver, même si quiver est plus dédié à tracer un champ vectoriel.

import matplotlib.pyplot as pltimport numpy as npX = 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()
Références
| Liens | Site |
|---|---|
| How to plot vectors in python using matplotlib | stackoverflow |
| matplotlib.pyplot.arrow | matplotlib doc |
| matplotlib arrow | matplotlib doc |
| matplotlib.pyplot.quiver | matplotlib doc |
| pylab_examples example code: quiver_demo.py | matplotlib doc |
| How do you get the magnitude of a vector in Numpy? | stackoverflow |
| annotate | matplotlib doc |
