Color maps¶
A color map turns numbers into colors. A poorly chosen color map can mislead a reader, and some readers cannot tell its colors apart. This notebook finds color maps with the Scicolor package, draws the same data with two color maps, checks color maps in gray scale, and shows the classes and types of color maps.
Sections: Install and import Scicolor, Find a color map, One dataset with two color maps, Color maps in gray scale, Classes and types of color maps.
Packages beyond the standard library: matplotlib, numpy, scicolor.
Install them with uv add matplotlib numpy scicolor (or pip install).
Colab has all of them except scicolor, and the first code cell installs it there.
# Colab does not have scicolor, so this cell installs it there.
# pip may print a note about restarting the kernel. A restart is not needed.
# The cell does nothing if scicolor is already installed.
import importlib.util
if importlib.util.find_spec("scicolor") is None:
%pip install -q scicolor
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scicolor
Find a color map¶
scicolor.list_cmaps() returns a table of all color maps of the package.
scicolor.list_cmaps()
The table has 79 rows, one for each color map, and 5 columns.
| cm_name | cm_class | cm_type | perceptually_uniform | color_blind_friendly | |
|---|---|---|---|---|---|
| 0 | tab20 | multi_sequential | categorical | False | False |
| 1 | tab20b | multi_sequential | categorical | False | False |
| ... | ... | ... | ... | ... | ... |
| 33 | batlow | sequential | continuous | True | True |
| ... | ... | ... | ... | ... | ... |
| 78 | Veronese | multi_sequential | discrete | False | True |
cm_classsays how the colors change. The section "Classes and types of color maps" below shows the classes.cm_typesays how many colors there are:continuous,discrete, orcategorical.perceptually_uniformisTruewhen equal steps in the data look like equal steps in color.color_blind_friendlyisTruewhen the color map stays readable for people with a color-vision deficiency.
Each column is also an argument of list_cmaps, which then returns only the rows that match.
scicolor.list_cmaps(color_blind_friendly=True)
67 of the 79 color maps are color-blind friendly.
The arguments can be combined. The next cell lists the diverging color maps that are continuous.
scicolor.list_cmaps(cm_class="diverging", cm_type="continuous")
The result has 6 rows: broc, cork, roma, managua, vik, and cwr.
scicolor.get_cmap returns one color map by its name.
A notebook shows a color map as a strip of its colors.
cmap = scicolor.get_cmap("batlow")
cmap
batlow goes from a dark blue through green and orange to a light pink.
It is a sequential color map: it gets steadily lighter from the first color to the last.
Pass the color map to a plot function with the cmap argument, as the next section does.
If the name does not exist, get_cmap prints a message and returns None.
One dataset with two color maps¶
The next cell computes a smooth surface with two peaks on a grid of 300 by 300 points.
The cell after it draws the surface twice with imshow: with the color map jet and with batlow.
jet is a rainbow color map.
It was the default of several plotting tools for many years and is still common.
Scicolor does not have it, so the cell takes it from Matplotlib by its name.
x = np.linspace(-3, 3, 300)
X, Y = np.meshgrid(x, x)
Z = np.exp(-((X + 1) ** 2 + Y ** 2)) + 0.6 * np.exp(-((X - 1.2) ** 2 + (Y - 0.5) ** 2) / 2)
Z.shape
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), layout="constrained")
for ax, name, cmap in zip(axes, ["jet", "batlow"], ["jet", scicolor.get_cmap("batlow")]):
image = ax.imshow(Z, cmap=cmap, origin="lower", extent=(-3, 3, -3, 3))
ax.set_title(name)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.colorbar(image, ax=ax, label="Value")
plt.show()
Both panels show the same numbers. The surface is smooth: it has no steps and no edges.
With jet, the panel shows bright bands in cyan and in yellow around the peaks.
The bands look like edges in the data, and the data has none.
The colors of jet change fast in some parts of the value range and slowly in other parts, so equal steps in the data do not look equal.
With batlow, the color changes evenly from the low values to the high values, and the panel shows no band.
Color maps in gray scale¶
A color map that gets steadily lighter keeps the order of the values when the figure is printed in black and white. Such a color map is also easier to read for people with a color-vision deficiency, because they can still see the lightness.
The function below turns each color of a color map into a gray value between 0 (black) and 1 (white). It uses a weighted sum of red, green, and blue. Green has the largest weight, because the eye is most sensitive to green.
def to_gray(cmap):
"""Return the gray values of 256 colors of a color map, from 0 (black) to 1 (white)."""
rgb = cmap(np.linspace(0, 1, 256))[:, :3]
return rgb @ [0.2126, 0.7152, 0.0722]
cmaps = {
"viridis": scicolor.get_cmap("viridis"),
"cividis": scicolor.get_cmap("cividis"),
"batlow": scicolor.get_cmap("batlow"),
"jet": matplotlib.colormaps["jet"],
}
for name, cmap in cmaps.items():
gray = to_gray(cmap)
print(f"{name:8} first {gray[0]:.2f} highest {gray.max():.2f} last {gray[-1]:.2f}")
viridis first 0.08 highest 0.87 last 0.87
cividis first 0.12 highest 0.88 last 0.88
batlow first 0.10 highest 0.85 last 0.85
jet first 0.04 highest 0.92 last 0.11
For viridis, cividis, and batlow, the last color is the lightest one.
For jet, the lightest color is in the middle, and the last color is almost as dark as the first.
The next cell draws each color map as a strip, next to the same strip in gray scale.
gradient = np.linspace(0, 1, 256).reshape(1, -1)
fig, axes = plt.subplots(len(cmaps), 2, figsize=(8, 2.6), layout="constrained")
for row, (name, cmap) in zip(axes, cmaps.items()):
row[0].imshow(gradient, aspect="auto", cmap=cmap)
row[1].imshow(to_gray(cmap).reshape(1, -1), aspect="auto", cmap="gray", vmin=0, vmax=1)
row[0].set_ylabel(name, rotation=0, ha="right", va="center")
for ax in axes.flat:
ax.set_xticks([])
ax.set_yticks([])
axes[0, 0].set_title("In color")
axes[0, 1].set_title("In gray scale")
plt.show()
The gray strips of viridis, cividis, and batlow go from dark to light in one direction.
A reader of a black-and-white print can still tell low values from high values.
The gray strip of jet is dark at both ends and light in the middle.
In a black-and-white print, the lowest and the highest values look almost the same.
Classes and types of color maps¶
The class of a color map says how its colors change:
- Sequential: the colors go from light to dark, or from dark to light. Use it for values from low to high, such as a count.
- Diverging: two sets of colors go in opposite directions from a neutral middle. Use it for values in two directions from a central value, such as a score from negative to positive.
- Multi-sequential: two sequential color maps are joined at a break. Use it when the values on the two sides of a threshold mean different things, such as heights below and above sea level.
- Cyclic: the last color is the same as the first color. Use it for values on a circle, such as the hour of the day.
The type of a color map says how many colors it has:
- Continuous: the colors change smoothly.
- Discrete: a few colors in a fixed order, for values in a few bins.
- Categorical: colors with no order, for groups such as platforms.
The next cell draws one example of each.
Scicolor has no cyclic color map, so the cell takes twilight from Matplotlib.
The categorical color map Archambault has seven colors.
examples = {
"sequential: batlow": scicolor.get_cmap("batlow"),
"diverging: vik": scicolor.get_cmap("vik"),
"multi-sequential: oleron": scicolor.get_cmap("oleron"),
"cyclic: twilight": matplotlib.colormaps["twilight"],
"continuous: batlow": scicolor.get_cmap("batlow"),
"discrete: batlow10": scicolor.get_cmap("batlow10"),
"categorical: Archambault": scicolor.get_cmap("Archambault"),
}
fig, axes = plt.subplots(len(examples), 1, figsize=(8, 3.6), layout="constrained")
for ax, (label, cmap) in zip(axes, examples.items()):
ax.imshow(gradient, aspect="auto", cmap=cmap)
ax.set_ylabel(label, rotation=0, ha="right", va="center")
ax.set_xticks([])
ax.set_yticks([])
plt.show()
The first four strips show the four classes, and the last three strips show the three types.
vikgoes from dark blue through white to dark red.oleronhas a break in the middle: shades of blue on one side, and green and brown on the other side.twilightstarts and ends with the same light color.batlow10has ten colors ofbatlowin the same order.Archambaulthas seven colors with no order: light blue, dark purple, muted purple, pink, red, orange, and yellow.