Themes, contexts and color palettes

seaborn · Essentials · 10 min

A consistent theme and the right palette type make charts readable and honest with almost no code.

sns.set_theme() applies seaborn's default look to all subsequent Matplotlib figures: the "darkgrid" style, the "notebook" context and the "deep" palette. Its arguments change each part:

  • style=: "darkgrid", "whitegrid", "dark", "white", "ticks". sns.despine() removes the top and right spines.
  • context=: "paper", "notebook", "talk", "poster" scale fonts and line widths for the destination; font_scale= fine-tunes.
  • palette=: the default color cycle.

sns.axes_style() and sns.plotting_context() also work as context managers for temporary changes.

Pick a palette by data type:

  • Qualitative for categories: "deep", "colorblind", "Set2", "tab10".
  • Sequential for ordered numbers: "rocket", "mako", "viridis", "Blues"; seaborn uses these automatically for numeric hue.
  • Diverging for values around a center: "vlag", "icefire", "RdBu".

sns.color_palette("mako", 5) returns a list of RGB colors you can reuse anywhere, and as_cmap=True returns a Matplotlib colormap. You can also pass a dict, palette={"control": "gray", "treatment": "C1"}, to pin specific colors to specific categories so they stay consistent across charts.

Use the "colorblind" palette in anything others will read, and avoid more than about eight qualitative colors; beyond that, colors become hard to tell apart.

Example

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import to_hex

sns.set_theme(style="whitegrid", context="talk", palette="colorblind")
print(plt.rcParams["font.size"])          # 18.0 (talk context is larger)

pal = sns.color_palette("mako", 3)
print(len(pal), to_hex(pal[0]))           # 3 #3e356b
cmap = sns.color_palette("vlag", as_cmap=True)
print(type(cmap).__name__)                # ListedColormap

fig, ax = plt.subplots()
sns.barplot(x=["control", "treatment"], y=[3.1, 3.8],
            hue=["control", "treatment"],
            palette={"control": "gray", "treatment": "C1"}, ax=ax)
sns.despine()
print(ax.spines["top"].get_visible())     # False
fig.savefig("themed.png")

Remember

  • set_theme sets style, context and palette together
  • Contexts scale everything for paper, notebook, talk or poster
  • Qualitative palettes for categories, sequential for magnitudes, diverging around a center

Watch out for

  • Using a sequential palette for unordered categories, implying a ranking that does not exist.

Check yourself

  1. You want consistent colors for 'control' and 'treatment' across ten different charts. What is the most robust choice?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: seaborn.pydata.org/tutorial/color_palettes.html