Book Image

Applying Math with Python - Second Edition

By : Sam Morley
Book Image

Applying Math with Python - Second Edition

By: Sam Morley

Overview of this book

The updated edition of Applying Math with Python will help you solve complex problems in a wide variety of mathematical fields in simple and efficient ways. Old recipes have been revised for new libraries and several recipes have been added to demonstrate new tools such as JAX. You'll start by refreshing your knowledge of several core mathematical fields and learn about packages covered in Python's scientific stack, including NumPy, SciPy, and Matplotlib. As you progress, you'll gradually get to grips with more advanced topics of calculus, probability, and networks (graph theory). Once you’ve developed a solid base in these topics, you’ll have the confidence to set out on math adventures with Python as you explore Python's applications in data science and statistics, forecasting, geometry, and optimization. The final chapters will take you through a collection of miscellaneous problems, including working with specific data formats and accelerating code. By the end of this book, you'll have an arsenal of practical coding solutions that can be used and modified to solve a wide range of practical problems in computational mathematics and data science.
Table of Contents (13 chapters)

Plotting vector fields with quiver plots

A vector field is a function that assigns to each point in a region a vector—it is a vector-valued function defined on a space. These are especially common in the study of (systems of) differential equations, where a vector field typically appears as the right-hand side of the equation. (See the Solving systems of differential equations recipe from Chapter 3 for more details.) For this reason, it is often useful to visualize a vector field and understand how the function will evolve over space. For now, we’re simply going to produce a plot of a vector field using a quiver plot, which takes a set of and coordinates and a set of and vectors, and produces a plot on which each point has an arrow in the direction and whose length is the length of this vector. (Hopefully, this will become more clear when we actually create the said plot.)

Getting ready

As usual, we import the Matplotlib pyplot interface under the alias plt. Before we start, we need to define a function that takes a point and produces a vector; we’ll use this later to generate and data that will be passed to the plotting function.

For this example, we’re going to plot the following vector field:

For this example, we’ll plot the vector field over the region where and .

How to do it…

The following steps show how to visualize the aforementioned vector field over the specified region.

First, we need to define a Python function that evaluates our vector field at points:

def f(x, y):
  v = x**2 +y**2
    return np.exp(-2*v)*(x+y), np.exp(
        -2*v)*(x-y)

Next, we need to create our grid of points covering the region. For this, we first create a temporary linspace routine with values between -1 and 1. Then, we use meshgrid to generate a grid of points:

t = np.linspace(-1., 1.)
x, y = np.meshgrid(t, t)

Next, we use our function to generate dx and dy values that describe the vectors at each grid point:

dx, dy = f(x, y)

Now, we can create a new figure and axis and use the quiver method to generate a plot:

fig, ax = plt.subplots()
ax.quiver(x, y, dx, dy)

The resulting plot is shown in Figure 2.10:

Figure 2.10 - Visualization of a vector field using a quiver plot

Figure 2.10 - Visualization of a vector field using a quiver plot

In Figure 2.10, we can see the value represented as an arrow based at each coordinate. The size of the arrow is determined by the magnitude of the vector field. At the origin, the vector field has , so the arrows nearby are very small.

How it works…

Our example from the recipe is a mathematical construction rather than something that might arise from real data. For this particular case, the arrows describe how some quantity might evolve if it flows according to the vector field we specified.

Each point in the grid is the base of an arrow. The direction of the arrow is given by the corresponding value, and the length of the arrow is normalized by length (so, a vector with smaller components produces a shorter arrow). This can be customized by changing the scale keyword argument. Many other aspects of the plot can be customized too.

There’s more…

If you want to plot a set of trajectories that follow a vector field, you can use the streamplot method. This will plot trajectories starting at various points to indicate the general flow in different parts of the domain. Each streamline has an arrow to indicate the direction of flow. For example, Figure 2.11 shows the result of using the streamplot method with the vector field in the recipe:

Figure 2.11 – Plot of the trajectories described by the vector field from the recipe

Figure 2.11 – Plot of the trajectories described by the vector field from the recipe

In a different scenario, you might have data about wind speed (or similar quantities) at a number of coordinates—on a map, say—and you want to plot these quantities in the standard style for weather charts. Then, we can use the barbs plotting method. The arguments are similar to the quiver method.