Colors & Colormaps
Colour is one of the strongest visual signals in a chart. Matplotlib accepts colours in many formats and ships with dozens of colormaps, which translate numbers into colours.
Ways to write a colour
| Format | Example | Notes |
|---|---|---|
| Named colour | "tomato", "steelblue" |
~150 CSS names |
| Single letter | "r", "k" |
8 basic colours |
| Hex string | "#2a9d8f", "#2a9d8f80" |
optional alpha as last two digits |
| RGB(A) tuple | (0.1, 0.4, 0.6), (1, 0, 0, 0.5) |
values from 0 to 1 |
| Grey level | "0.75" |
string between 0 (black) and 1 (white) |
| Cycle colour | "C0" … "C9" |
the default colour cycle |
| Tableau colours | "tab:blue", "tab:orange" |
same as the default cycle |
| xkcd colours | "xkcd:sky blue" |
954 names from a survey |
matplotlib.colors converts between them:
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
samples = ["tomato", "#2a9d8f", (0.2, 0.3, 0.8), "0.6", "C1", "tab:purple", "xkcd:sky blue"]
fig, ax = plt.subplots(figsize=(7, 2))
for i, c in enumerate(samples):
ax.bar(i, 1, color=c)
ax.set_xticks(range(len(samples)), [str(s) for s in samples], rotation=20, fontsize=8)
ax.set_yticks([])
plt.tight_layout()
plt.show()
for c in samples:
print(f"{str(c):<16} -> {mcolors.to_hex(c)}")tomato -> #ff6347
#2a9d8f -> #2a9d8f
(0.2, 0.3, 0.8) -> #334ccc
0.6 -> #999999
C1 -> #ff7f0e
tab:purple -> #9467bd
xkcd:sky blue -> #75bbfd
Transparency
alpha (0 = invisible, 1 = opaque) works on almost every artist. Overlapping semi-transparent shapes reveal where they overlap:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
fig, ax = plt.subplots(figsize=(4, 4))
for (x, y), c in zip([(0.4, 0.6), (0.6, 0.6), (0.5, 0.42)], ["red", "green", "blue"]):
ax.add_patch(Circle((x, y), 0.25, color=c, alpha=0.35))
ax.set_aspect("equal")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis("off")
plt.show()
print("Patches drawn:", len(ax.patches), "| alpha:", ax.patches[0].get_alpha())Patches drawn: 3 | alpha: 0.35
Colormaps
A colormap maps a number between 0 and 1 to a colour. Matplotlib groups them by purpose:
| Kind | Use for | Examples |
|---|---|---|
| Sequential | Values from low to high | viridis, plasma, Blues, Greens, magma |
| Diverging | Values around a meaningful centre (0, average) | coolwarm, RdBu, PiYG, seismic |
| Qualitative | Unordered categories | tab10, Set2, Pastel1, Dark2 |
| Cyclic | Angles, time of day | twilight, hsv |
import numpy as np
import matplotlib.pyplot as plt
names = ["viridis", "plasma", "Blues", "coolwarm", "RdBu", "tab10", "twilight"]
gradient = np.linspace(0, 1, 256).reshape(1, -1)
fig, axes = plt.subplots(len(names), 1, figsize=(6, 3.5))
for ax, name in zip(axes, names):
ax.imshow(gradient, aspect="auto", cmap=name)
ax.set_axis_off()
ax.text(-0.01, 0.5, name, transform=ax.transAxes, ha="right", va="center", fontsize=9)
fig.subplots_adjust(left=0.2, right=0.98, top=0.98, bottom=0.02, hspace=0.4)
plt.show()
print("Colormaps shown:", len(names))Colormaps shown: 7
Tip: Prefer perceptually uniform maps like
viridis(the default) for sequential data. Equal steps in value look like equal steps in colour, they stay readable in grayscale, and they work for most colour-blind readers. Avoidjetandrainbow: they create false "edges" in smooth data.
Picking colours from a colormap
Calling a colormap object with a number in 0–1 returns an RGBA tuple. This is handy to colour a family of lines in order:
import numpy as np
import matplotlib.pyplot as plt
cmap = plt.get_cmap("plasma")
x = np.linspace(0, 1, 100)
fig, ax = plt.subplots()
for i, k in enumerate(range(1, 8)):
ax.plot(x, x ** k, color=cmap(i / 7), label=f"k = {k}")
ax.legend(title=r"$y = x^kquot;, fontsize=8)
plt.show()
r, g, b, a = cmap(0.0)
print(f"plasma(0.0) = ({r:.3f}, {g:.3f}, {b:.3f}, {a})")
print("plasma has", cmap.N, "colours")plasma(0.0) = (0.050, 0.030, 0.528, 1.0)
plasma has 256 colours
Reversed maps and custom maps
Add _r to any name for the reversed version ("viridis_r", "Blues_r"). You can also build your own map from a list of colours:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
ocean = LinearSegmentedColormap.from_list("ocean", ["#03045e", "#0077b6", "#90e0ef", "#ffffff"])
traffic = ListedColormap(["#2a9d8f", "#e9c46a", "#e76f51"])
data = np.linspace(0, 1, 100).reshape(10, 10)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3.5))
im1 = ax1.imshow(data, cmap=ocean)
ax1.set_title("Smooth custom map")
im2 = ax2.imshow(data, cmap=traffic)
ax2.set_title("3-colour listed map")
fig.colorbar(im1, ax=ax1)
fig.colorbar(im2, ax=ax2)
plt.show()
print("ocean:", ocean.N, "steps | traffic:", traffic.N, "colours")ocean: 256 steps | traffic: 3 colours
LinearSegmentedColormap blends smoothly between the given colours; ListedColormap uses exactly those colours as discrete bands.
Test yourself
Which colormap type suits data with a meaningful centre, like temperature anomalies around 0?
- Sequential
- Diverging
- Qualitative
- Cyclic
How do you get the reversed version of the Blues colormap?
- "Blues".reverse()
- "-Blues"
- "Blues_r"
- cmap="Blues", reverse=True
What does plt.get_cmap("viridis")(0.5) return?
- The name of the colour
- An RGBA tuple for the middle of the map
- A list of 256 colours
- An error