Skip to content
Home » matplotlib Part 24 – Colorbars

matplotlib Part 24 – Colorbars

Spread the love

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]:
<matplotlib.collections.PolyCollection at 0x1bd2be249c8>

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]:
<matplotlib.colorbar.Colorbar at 0x1bd2cf38d88>

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]:
<matplotlib.contour.QuadContourSet at 0x1bd2cf98ec8>

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]:
<matplotlib.colorbar.Colorbar at 0x1bd2e6f5e08>

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply