Contour Plots
In the previous article we were talking about color maps. Today we’ll be talking about contour maps, which are pretty similar. Instead of the pcolor method, you use the contour method. So, let’s recreate the example from the previous article first:
In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# Let's create the x and y values.
x = y = np.linspace(0, 10, 100)
# Let's format the data.
X, Y = np.meshgrid(x, y)
# Let's define the values of Z.
Z = np.sin(X) ** 5 + np.cos(Y) * np.cos(X)
# Let's create the color map
fig, ax = plt.subplots()
ax.pcolor(X, Y, Z)
Out[1]:
And now let’s change it to a contour plot:
In [2]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z)
Out[2]:
Just like with the color map, you can set the cmap argument to one of the predefined values:
In [3]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.bwr)
Out[3]:
In [4]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.Dark2)
Out[4]:
In [5]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, cmap=mpl.cm.hot)
Out[5]:
You can also set one color by passing a single value to the colors argument. Then positive values are represented by solid lines and negative ones by dashed lines:
In [6]:
# set color to black
fig, ax = plt.subplots()
ax.contour(X, Y, Z, colors='k')
Out[6]:
You can also specify more than one color:
In [7]:
fig, ax = plt.subplots()
ax.contour(X, Y, Z, colors=['k', 'r'])
Out[7]:
We can also create a contour plot with the spaces between the lines filled. To this end we use the contourf method:
In [8]:
fig, ax = plt.subplots()
ax.contourf(X, Y, Z)
Out[8]: