# 5 Best Ways to Plot Vectors in Python Using Matplotlib

Rate this post

π‘ Problem Formulation: When working with linear algebra or physics problems in Python, there’s often a need to visualize vectors for better understanding and communication of data. Users typically have vectors in form of tuples or lists, such as `(x, y)` or `[x, y, z]`, and seek a way to create graphical representations of these vectors. This article explores how to use Python’s matplotlib library to plot vectors, specifying both magnitude and direction.

## Method 1: Basic Vector Plotting with Quiver

Matplotlib’s `quiver` function is specifically designed for plotting vectors. This method handles 2D vector fields and can also be adapted for 3D vectors with some tweaking. The `quiver` function plots a 2D field of arrows, with vectors positioned at the grid points defined by the user.

Here’s an example:

```import matplotlib.pyplot as plt

soa = np.array([[0, 0, 1, 1], [1, 1, -2, -2]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
plt.draw()
plt.show()```

Output: A plot displaying both vectors β one heading top-right and the other bottom-left.

The code snippet uses the `quiver` function to create a plot with arrows representing the vectors. `X` and `Y` are the starting points of the vectors, while `U` and `V` are their directional components. The plot limits are set with `ax.set_xlim()` and `ax.set_ylim()` to provide a better view of the vectors.

## Method 2: Enhanced Vector Visualization Using Quiver with Customizations

Enhancing vector plots can be achieved by customizing the arrows with different colors, sizes, and other properties to represent additional variables like vector magnitude. This can yield a more informative visual.

Here’s an example:

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

soa = np.array([[0, 0, 2, 1], [1, 1, -1, -1.5]])
X, Y, U, V = zip(*soa)
colors = ['r','b']
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color=colors)
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
plt.draw()
plt.show()```

Output: A plot with two distinctly colored vectors; one in red and another in blue.

This code snippet extends the basic functionality by adding colors. Each vector is assigned a color representing a different characteristic or category. The color argument `color=colors` is added to `ax.quiver()` to achieve this effect.

## Method 3: 3D Vector Plotting with Quiver3D

For 3D vectors, Matplotlib’s `mplot3d` toolkit includes the `quiver3D` function which works similarly to `quiver` but adds a third dimension, allowing visualization of spatial vector data.

Here’s an example:

```from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

soa = np.array([[0, 0, 0, 1, 1, 1], [0, 0, 0, -1, -2, 0]])
X, Y, Z, U, V, W = zip(*soa)
fig = plt.figure()
ax.quiver(X, Y, Z, U, V, W)
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])
plt.show()```

Output: A 3D plot with vectors extending into the three-dimensional space.

The snippet uses the `quiver3D` function to plot 3D vectors. `soa` now includes `Z` position and `W` vector component for the third dimension. The `Axes3D` constructor is used to initialize a 3D plot.

## Method 4: Combining Vectors with Head-To-Tail Method

When combining multiple vectors, the head-to-tail method is often used. This involves plotting vectors sequentially such that the head of one vector connects to the tail of the next. Matplotlib can be used to visualize this process and the resultant vector.

Here’s an example:

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

vectors = np.array([[0, 0, 2, 3], [2, 3, -1, 1], [1, 4, 3, -2]])
origin = np.array([[0, 0, 0, 0], [0, 0, 0, 0]]) # origin point

plt.quiver(*origin, vectors[:,0], vectors[:,1], color=['r','b','g'], scale=21)
plt.xlim(-2, 6)
plt.ylim(-2, 6)
plt.show()```

Output: A plot of vectors in sequence with their combined vector represented in green.

The script creates a quiver plot, with vectors placed head-to-tail. The `origin` defines the starting point for the vectors. The plot window is adjusted to display all vectors without clipping.

## Bonus One-Liner Method 5: Quick Vector Plotting with Complex Numbers

Python and matplotlib also allow for an elegant one-liner approach to plotting vectors using complex numbers. Here, vectors are represented as complex numbers, which are inherently composed of a real (x-component) and an imaginary part (y-component).

Here’s an example:

```import matplotlib.pyplot as plt

vectors = np.array([complex(1,2), complex(2,-3)])
plt.quiver(np.real(vectors), np.imag(vectors), angles='xy', scale_units='xy', scale=1)
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.show()```

Output: A succinct plot showing the vectors visualized using the complex number representation.

This method takes advantage of NumPy’s handling of complex numbers to plot vectors succinctly. `np.real` and `np.imag` extract the requisite components for the quiver function.

## Summary/Discussion

• Method 1: Basic Quiver Plotting. Provides a straightforward way to plot vectors. Limited in that it doesn’t accommodate different styling out-of-the-box.
• Method 2: Customized Quiver Plotting. Allows for color customization and therefore greater detail can be represented. More code required for each vector property.
• Method 3: 3D Vector Quiver3D. Best for visualizing spatial vector data. Can be more computationally intensive, and may require 3D visualization facilities.
• Method 4: Head-To-Tail Vectors. Useful for illustrating vector addition. Depends on careful data preparation to align vectors head-to-tail.
• Method 5: Complex Number Plotting. Elegant for quick plotting. Only practical for simple vectors and when comfortable with complex numbers.