Chapter 2 · Practice 2 of 4
Label series directly instead of relying on a legend
From Encoding and clutter
Why it matters
The Analysis Function advises avoiding legends where possible, because they rely on color to match labels to data, and recommends labelling lines directly. Direct labels also mean readers do not have to move their eyes back and forth.
In matplotlib, ax.bar_label adds value labels to bars, and ax.annotate or ax.text can place a series name at the end of each line. If you must keep a legend, match its order to the order of the data on the chart.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
for name, series in df.groupby("plan"):
ax.plot(series["month"], series["signups"], color=colors[name])
last = series.iloc[-1]
ax.annotate(name, (last["month"], last["signups"]),
xytext=(6, 0), textcoords="offset points", va="center")
ax.spines[["top", "right"]].set_visible(False)