Saturday, January 25, 2020

Contour and Vector Field Plots

matplotlib has extensive tools for creating and annotating two dimensional contour plots and vector field plots. A contour plot is used to visualize two-dimensional scalar functions, such as the electric potential V (x;y) or elevations h(x;y) over some physical terrain. Vector field plots come in different varieties. There are field line plots, which in some contexts are called streamline plots, that show the direction of a vector field over some 2D (x;y) range. There are also quiver plots, which consist essentially of a 2D grid of arrows, that give the direction and magnitude of a vector field over some 2D (x;y) range.

Lets see how to make a 2D grid of points.When plotting a function f (x) of a single variable, the first step is usually to create a one-dimensional x array of points, and then to evaluate and plot the function f (x) at those points, often drawing lines between the points to create a continuous curve. Similarly, when making a two dimensional plot, we usually need to make a two-dimensional x-y array of points, and then to evaluate and plot the function f (x;y), be it a scaler or vector function, at those points, perhaps with continuous curves to indicate the value of the function over the 2D surface.
Thus, instead of having a line of evenly spaced x points, we need a grid of evenly spaced x-y points. Fortunately, NumPy has a function np.meshgrid for doing just that. The procedure is first to make an xarray at even intervals over the range of x to be covered, and then to do the same for y. These two one-dimensional arrays are used as input to the np.meshgrid function, which makes a two- dimensional mesh. The following program shows how it works:

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

x = np.linspace(-1, 1, 5)
y = np.linspace(2, 6, 5)

X, Y = np.meshgrid(x, y)

plt.plot(X, Y, 'o')
plt.show()

The output of plot(X, Y, 'o') is a 2D grid of points, as shown in figure below.


matplotlib’s functions for making contour plots and vector field plots generally use the output of gridmesh as the 2D input for the functions to be plotted. In the next post we'll see how to create contour plots.
Share:

0 comments:

Post a Comment