Comment tracer un simple vecteur avec matplotlib ?


Pour tracer un simple vecteur avec matplotlib on peut utiliser arrow

Tracer un simple vecteur avec matplotlib

Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?
Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?

import matplotlib.pyplot as plt
import numpy as np

ax = 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).

Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?
Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?

import matplotlib.pyplot as plt
import numpy as np
import math

a = [2.0,4.0]
b = [8.0,8.0]

head_length = 0.7

dx = 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_magnitude
dy = dy / vec_ab_magnitude

vec_ab_magnitude = vec_ab_magnitude - head_length

ax = 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.

Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?
Comment tracer un vecteur ou un champ vectoriel avec matplotlib ?

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()

Références

Image

of