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 ...

Get matplotlib Plotting Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.