How to plot a simple vector with matplotlib ?


To plot a simple vector using matplotlib a solution is to use arrow

Plot a simple vector with matplotlib

How to plot a simple vector with matplotlib ?
How to plot a simple vector with 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()

Plot a vector defined by two points

An example of how to plot a vector between two points A and B with matplotlib, taking into account the head_length:

How to plot a simple vector with matplotlib ?
How to plot a simple vector with 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()

Plot a vector using quiver

It is also possible to plot a simple vector using matplotlib quiver function, even if quiver is more for plotting vector field:

How to plot a simple vector with matplotlib ?
How to plot a simple vector with 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()

References

Image

of