plt.contour
for contour plots, plt.contourf
for filled contour plots, and plt.imshow
for showing images.
This section looks at several examples of using these. We'll start by setting up the notebook for plotting and importing the functions we will use:%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
plt.contour
function.
It takes three arguments: a grid of x values, a grid of y values, and a grid of z values.
The x and y values represent positions on the plot, and the z values will be represented by the contour levels.
Perhaps the most straightforward way to prepare such data is to use the np.meshgrid
function, which builds two-dimensional grids from one-dimensional arrays:x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contour(X, Y, Z, colors='black');
cmap
argument.
Here, we'll also specify that we want more lines to be drawn—20 equally spaced intervals within the data range:plt.contour(X, Y, Z, 20, cmap='RdGy');
RdGy
(short for Red-Gray) colormap, which is a good choice for centered data.
Matplotlib has a wide range of colormaps available, which you can easily browse in IPython by doing a tab completion on the plt.cm
module:plt.cm.<TAB>
plt.contourf()
function (notice the f
at the end), which uses largely the same syntax as plt.contour()
.plt.colorbar()
command, which automatically creates an additional axis with labeled color information for the plot:plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar();
plt.imshow()
function, which interprets a two-dimensional grid of data as an image.plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image');
imshow()
, however:plt.imshow()
doesn't accept an x and y grid, so you must manually specify the extent [xmin, xmax, ymin, ymax] of the image on the plot.plt.imshow()
by default follows the standard image array definition where the origin is in the upper left, not in the lower left as in most contour plots. This must be changed when showing gridded data.plt.imshow()
will automatically adjust the axis aspect ratio to match the input data; this can be changed by setting, for example, plt.axis(aspect='image')
to make x and y units match.alpha
parameter) and overplot contours with labels on the contours themselves (using the plt.clabel()
function):contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();