Legends and Colors
Legends
Section titled “Legends”Legends are needed when you plot multiple series. McKinney is clear about one gotcha
here: passing label="..." to plot() doesn’t draw a legend by itself — you must
still call ax.legend() afterwards, whether or not you set labels beforehand.
flowchart LR A["ax.plot(x, y1, label='square')"] --> C["ax.legend()"] B["ax.plot(x, y2, label='linear')"] --> C C --> D["Legend box appears, one entry per label"]
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
plt.figure(figsize=(7, 4))
plt.plot(x, y1, label="square")
plt.plot(x, y2, label="linear")
plt.title("Two series")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.tight_layout()
plt.show()Colors
Section titled “Colors”Use:
- high-contrast colors
- colorblind-friendly palettes when possible
- consistent color meaning across charts
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 4))
plt.plot([1, 2, 3], [3, 2, 5], color="#1f77b4")
plt.title("Custom color")
plt.tight_layout()
plt.show()Avoid using too many colors in one chart.
Continue to Saving Plots as Images to export your finished, labelled charts.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Label a series and show the legend
Section titled “Exercise 1 – Label a series and show the legend”Exercise 2 – Use a hex color code
Section titled “Exercise 2 – Use a hex color code”Exercise 3 – Hide a series from the legend
Section titled “Exercise 3 – Hide a series from the legend”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading