How to Plot Vectors Using Python Matplotlib

Manav Narula Feb 02, 2024
  1. Use the matplotlib.axes.Axes.arrow() Function to Plot a Vector Using Python matplotlib
  2. Use the matplotlib.pyplot.quiver() Function to Plot a Vector Using matplotlib in Python
How to Plot Vectors Using Python Matplotlib

A vector is an object in vector space that has magnitude and direction. We can represent vectors using arrays in Python.

We need to specify its direction on the graph for plotting vectors like an arrow. We can use the matplotlib library, which is highly used to create different graphs and plot vectors in Python.

Let us understand how to plot vectors using Python’s matplotlib library.

Use the matplotlib.axes.Axes.arrow() Function to Plot a Vector Using Python matplotlib

We will add an Axes to the current figure to plot a simple single vector using the ax.axes() function.

To plot the vector on these Axes, we will use the Axes.arrow() function. It creates an arrow from the given x and y coordinates to the specified start to finish values.

We will implement this on the following graph.

import matplotlib.pyplot as plt

ax = plt.axes()
ax.arrow(1, 2, 5, 5, head_width=0.5, head_length=0.5)
plt.ylim(0, 10)
plt.xlim(0, 10)
plt.show()

Output:

plot vectors using the arrow function

We plot the required vector from coordinates (1,2) to (5,5) in the above example.

The head_width and head_length parameters are used to specify the arrow head’s width and length, respectively. We can also customize the final plot with other parameters like shape and overhang.

Use the matplotlib.pyplot.quiver() Function to Plot a Vector Using matplotlib in Python

The pyplot.quiver() function can create a plot of a field of arrows in a 2D figure. We can use it to plot multiple vectors at once.

We need to start by initializing the coordinates of the vectors and the origin point of the graph. For this, we will use a numpy array.

We will then use the pyplot.quiver() function to create a plot using these coordinates.

See the example below.

import numpy as np
import matplotlib.pyplot as plt

coordinates = np.array([[2, 5], [1, 4]])
o = np.array([[0, 0], [0, 0]])
plt.quiver(*o, coordinates[:, 0], coordinates[:, 1], color=["blue", "green"], scale=15)
plt.ylim(-10, 10)
plt.xlim(-10, 10)
plt.show()

Output:

plot vectors using the quiver function

We plotted two vectors using the pyplot.quiver() function above.

The origin has been specified using the o array. We scale the dimensions of the arrow to an appropriate size using the scale parameter.

We can customize the final plot and change the shape and size of the arrowheads using different parameters like headlength, headwidth, headaxislength, and more.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn