Colorbars
In the preceding articles we were talking about colormap plots and contour plots. We know that the colors represent the Z values, whereas the X and Y values are represented by position in a 2D coordinate system. But what do the colors mean? What values of Z do they correspond to? In order to make it clear, we should add a color legend, or a colorbar.
Let’s recreate one of the examples we used before:
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]:
Some areas are blue, others are yellow or green, in various shades. But are blue values higher or lower than the yellow one? Let’s check it out. To add a colorbar we use the colorbar method:
In [2]:
fig, ax = plt.subplots()
# We assign the colormap to a variable.
p = ax.pcolor(X, Y, Z)
# We pass the colormap to the colorbar.
fig.colorbar(p)
Out[2]:
You can tweak the ticks on the colorbar. Let’s reduce their number:
In [3]:
fig, ax = plt.subplots()
p = ax.pcolor(X, Y, Z)
# We assign the colorbar to a variable.
cbar = fig.colorbar(p)
# We set the ticks.
cbar.set_ticks([-1, 0, 1])
Here’s our contour plot example:
In [4]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) ** 5 + np.cos(Y) * np.cos(X)
fig, ax = plt.subplots()
ax.contour(X, Y, Z)
Out[4]:
Let’s add a colorbar to it:
In [5]:
fig, ax = plt.subplots()
# We assign the contour to a variable.
p = ax.contourf(X, Y, Z)
# We pass the contour to the colorbar.
fig.colorbar(p)
Out[5]: