Heatmaps & Colorbars
A heatmap shows a 2-D grid of numbers as coloured cells: a correlation matrix, sales per weekday and hour, the pixels of an image. Matplotlib draws them with imshow() (for regular grids) or pcolormesh() (for grids with arbitrary cell edges). A colorbar next to the plot translates colours back into values.
imshow() and colorbar()
ax.imshow(array2d) draws one cell per array element. Row 0 is at the top, as in an image:
import numpy as np
import matplotlib.pyplot as plt
grid = np.array([
[1, 2, 3, 4],
[2, 4, 6, 8],
[3, 6, 9, 12],
])
fig, ax = plt.subplots()
im = ax.imshow(grid, cmap="viridis")
fig.colorbar(im, ax=ax, label="value")
ax.set_title("A 3 × 4 grid")
plt.show()
print("shape:", grid.shape)
print("colour range:", im.get_clim())shape: (3, 4)
colour range: (1, 12)
imshow returns an AxesImage. Pass it to fig.colorbar() so the bar uses the same colormap and value range. get_clim() returns that range: by default the minimum and maximum of the data.
Labelled heatmap with values
Real heatmaps need row/column labels and often the numbers themselves. Here is the number of support tickets per weekday and time slot:
import numpy as np
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
slots = ["0-4", "4-8", "8-12", "12-16", "16-20", "20-24"]
tickets = np.array([
[3, 8, 42, 38, 25, 9],
[2, 7, 39, 35, 22, 8],
[4, 9, 36, 33, 24, 10],
[3, 6, 40, 37, 27, 11],
[5, 10, 33, 29, 30, 15],
[7, 4, 14, 18, 20, 17],
[6, 3, 11, 15, 16, 14],
])
fig, ax = plt.subplots(figsize=(7, 5))
im = ax.imshow(tickets, cmap="YlOrRd")
ax.set_xticks(range(len(slots)), slots)
ax.set_yticks(range(len(days)), days)
ax.set_xlabel("Time of day")
for i in range(len(days)):
for j in range(len(slots)):
value = tickets[i, j]
color = "white" if value > 30 else "black" # keep text readable on dark cells
ax.text(j, i, value, ha="center", va="center", color=color, fontsize=9)
fig.colorbar(im, ax=ax, label="Tickets")
ax.set_title("Support tickets per slot")
fig.tight_layout()
plt.show()
d, s = np.unravel_index(tickets.argmax(), tickets.shape)
print("Busiest slot:", days[d], slots[s], "with", tickets[d, s], "tickets")Busiest slot: Mon 8-12 with 42 tickets
Cell centres are at integer positions (column, row), which is why ax.text(j, i, ...) places each number in its cell.
Correlation matrix with a diverging map
Correlations run from −1 to +1 with a meaningful centre at 0, so a diverging colormap with fixed limits vmin=-1, vmax=1 is the right choice. Then 0 is always the neutral middle colour:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
n = 200
hours = rng.uniform(0, 10, n)
score = 50 + 4 * hours + rng.normal(0, 8, n)
sleep = 8 - 0.2 * hours + rng.normal(0, 0.8, n)
coffee = rng.poisson(2, n) + 0.1 * hours
names = ["study", "score", "sleep", "coffee"]
corr = np.corrcoef([hours, score, sleep, coffee])
fig, ax = plt.subplots()
im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1)
ax.set_xticks(range(4), names)
ax.set_yticks(range(4), names)
for i in range(4):
for j in range(4):
color = "white" if abs(corr[i, j]) > 0.5 else "black"
ax.text(j, i, f"{corr[i, j]:.2f}", ha="center", va="center", color=color, fontsize=9)
fig.colorbar(im, ax=ax, label="correlation")
plt.show()
print(np.round(corr, 2))[[ 1. 0.81 -0.6 0.24]
[ 0.81 1. -0.47 0.14]
[-0.6 -0.47 1. -0.17]
[ 0.24 0.14 -0.17 1. ]]
imshow options
| Argument | Effect |
|---|---|
cmap |
colormap name or object |
vmin, vmax |
fix the value range of the colours |
norm |
non-linear mapping, e.g. matplotlib.colors.LogNorm() |
aspect |
"equal" (square cells, default) or "auto" (fill the Axes) |
origin |
"upper" (row 0 on top, default) or "lower" |
extent |
(left, right, bottom, top) in data coordinates |
interpolation |
"nearest" for crisp cells, "bilinear" for smooth images |
Heatmaps of functions
With extent and origin="lower", imshow can display a function of two variables on real coordinates. np.meshgrid builds the x and y grids:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 200)
y = np.linspace(-2, 2, 150)
X, Y = np.meshgrid(x, y)
Z = np.sin(X ** 2 + Y) * np.exp(-0.2 * (X ** 2 + Y ** 2))
fig, ax = plt.subplots(figsize=(7, 4))
im = ax.imshow(Z, extent=(-3, 3, -2, 2), origin="lower", cmap="coolwarm",
vmin=-1, vmax=1, aspect="auto")
fig.colorbar(im, ax=ax, shrink=0.9)
ax.set(xlabel="x", ylabel="y", title=r"$z = \sin(x^2 + y)\,e^{-0.2(x^2+y^2)}quot;)
plt.show()
print("grid shape:", Z.shape, "| range:", round(float(Z.min()), 2), "to", round(float(Z.max()), 2))grid shape: (150, 200) | range: -0.7 to 0.78
The grid has 150 rows (y) and 200 columns (x): NumPy arrays are indexed [row, column], i.e. [y, x].
pcolormesh for uneven cells
pcolormesh(x_edges, y_edges, values) takes the edges of the cells, so cells may have different sizes, for example age groups of different widths:
import numpy as np
import matplotlib.pyplot as plt
age_edges = [0, 18, 30, 45, 65, 90]
year_edges = [2019, 2020, 2021, 2022, 2023, 2024]
rate = np.array([
[12, 25, 31, 28, 20],
[13, 27, 30, 29, 22],
[15, 30, 33, 30, 24],
[16, 33, 35, 31, 26],
[18, 36, 37, 33, 27],
]) # rows = years, columns = age groups
fig, ax = plt.subplots()
mesh = ax.pcolormesh(age_edges, year_edges, rate, cmap="Greens", edgecolors="white")
fig.colorbar(mesh, ax=ax, label="Usage (%)")
ax.set(xlabel="Age", ylabel="Year", title="Cells of unequal width")
plt.show()
print("cells:", rate.size, "| widest age group:", max(np.diff(age_edges)), "years")cells: 25 | widest age group: 25 years
Test yourself
Why pass the result of imshow to fig.colorbar()?
- To save the image
- So the colorbar uses the same colormap and value range
- To make the image square
- It is optional and ignored
For a correlation matrix, why set vmin=-1, vmax=1?
- To speed up drawing
- So that 0 sits at the neutral centre of a diverging colormap
- Because imshow requires it
- To hide the diagonal
By default, where does row 0 of the array appear in imshow?
- At the bottom
- At the top
- On the left
- In the centre