Skip to content

Plotting Vector Fields in Python

Python's matplot library, matplotlib, has all the functions you need to compute and plot vector fields. We'll be using the numpy function meshgrid to make a two-dimensional array of points at which to plot the arrows and matplotlib's quiver function to create the vectors.

The quiver function has two different types of inputs. The first two inputs are the \(x\) and \(y\) coordinates where the vectors will be plotted and the last two are the functions that determine the components of the vectors at those points.

Below are a few examples to give you a feel for using these functions followed by some exercises for you to try.

Example 1: Plot the vector field \(\vec{V}(x,y) = \hat{x}-\hat{y}\).

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots() #Setup figure

x,y = np.meshgrid(np.linspace(-5,5,10),np.linspace(-5,5,10))

u = 1
v = -1

plt.quiver(x,y,u,v)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

png

The linspace function makes an array of values starting at its first argument and ending at its second argument with as many values as its final argument. Copy and past the above code and try adjusting these parameters. You'll notice that quiver automatically adjusts the size of the arrows depending on how many you display.

Example 2: Here's a less simple example where the components of the vector field depend on position, \(\vec{V}(x,y) = y \hat{x} - xy \hat{y}\).

x,y = np.meshgrid(np.linspace(-5,5,10),np.linspace(-5,5,10))
fig, ax = plt.subplots() #Setup figure

u = y
v = -x*y

plt.quiver(x,y,u,v)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

png

Exercise (a): Consider the \(xy\) plane in polar coordinates \((r,\phi)\). Find the polar unit vector \(\hat{r}\) in Cartesian coordinates. (N.B. This is a vector field and depends on which point of the plane you are at.) Plot your result and confirm that it makes sense.

Exercise (b): Same setup as in 1. Find the unit vector \(\hat{\phi}\) in Cartesian coordinates. Plot your result and confirm that it makes sense.

Excercise (c): Take any of the three-dimensional vector fields that you have worked with in the first two problem sets or read about in the first chapter of Griffiths. Evaluate this vector field in the \(xy\) plane, and then project it onto the \(xy\) plane. Finally make a plot of your result using the tools above. (Here I want you to think through what it means to evaluate the vector field in the \(xy\) plane and what it means to project it onto this plane. You should identify the mathematical procedures that accomplish each of these things and what they mean geometrically. Explain your procedures and what they mean briefly in English too.)