Consistent, accessible colors make charts readable, and style sheets let you change a whole report's look in one line.
Matplotlib accepts colors in many forms:
- named colors:
"red","steelblue"; - the Tableau palette used by default:
"tab:blue","tab:orange"...; - hex strings
"#11557C"or RGB(A) tuples of floats(0.1, 0.3, 0.5, 0.8); "C0","C1"... meaning the nth color of the current property cycle;- a grayscale string such as
"0.6".
When you do not pass a color, each new line or bar group takes the next entry of the cycle. Using "C0" explicitly lets you match a line and its shaded band without hard-coding a value.
Markers ("o", "s", "^", "x", "."), line styles ("-", "--", ":") and widths complete the look. Redundant encoding, such as color plus marker or line style, keeps charts readable in grayscale and for color-blind readers.
Style sheets change many defaults at once: fonts, grid, colors, background. plt.style.available lists the built-ins ("ggplot", "seaborn-v0_8-whitegrid", "fivethirtyeight", "tableau-colorblind10" ...). Apply one globally with plt.style.use("ggplot"), or temporarily:
with plt.style.context("dark_background"):
fig, ax = plt.subplots()Styles are applied when artists are created, so switch style before making the figure, not after.
For colors that encode numbers, do not hand-pick: use a colormap, covered with images and heatmaps.
Example
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
print(to_hex("tab:blue"), to_hex("C1")) # #1f77b4 #ff7f0e
print(to_hex((0.0, 0.5, 1.0))) # #0080ff
print("ggplot" in plt.style.available) # True
with plt.style.context("tableau-colorblind10"):
fig, ax = plt.subplots()
for k, m in enumerate(["o", "s", "^"]):
ax.plot([0, 1, 2], [k, k + 1, k + 0.5], marker=m, label=f"series {k}")
print(to_hex(ax.lines[0].get_color())) # #006ba4 (from that style's cycle)
ax.legend()
fig.savefig("styled.png")Remember
- Colors can be names,
tab:colors, hex, RGB tuples or cycle refsC0..C9 - Encode series with color plus marker or line style for accessibility
plt.style.context(...)applies a style sheet temporarily; set it before creating the figure
Watch out for
- Switching style after creating a figure and expecting existing artists to change.