Visualizing a 2D scalar field
matplotlib and NumPy offer some interesting mechanisms that make the visualization of a 2D scalar field convenient. In this recipe, we show a very simple way to visualize a 2D scalar field.
How to do it...
The numpy.meshgrid()
function generates the samples from an explicit 2D function. Then, pyplot.pcolormesh()
is used to display the function, as shown in the following code:
import numpy as np from matplotlib import pyplot as plt import matplotlib.cm as cm n = 256 x = np.linspace(-3., 3., n) y = np.linspace(-3., 3., n) X, Y = np.meshgrid(x, y) Z = X * np.sinc(X ** 2 + Y ** 2) plt.pcolormesh(X, Y, Z, cmap = cm.gray) plt.show()
The preceding script will produce the following output:
Note how a sensible choice of colormap can be helpful; here, negative values appear in black and positive values appear in white. Thus, we have the sign and magnitude information visible at a glance. Use a colormap going from red to blue with white at the middle of the scale...