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
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()Tip
Avoid using too many colors in one chart.
Check your understanding
You pass label="square" to plt.plot but never call plt.legend(). What appears?
You must call legend() afterwards, whether or not you set labels beforehand.
Show answer
A — No legend, because labels alone do not draw one — You must call legend() afterwards, whether or not you set labels beforehand.
Which color argument is used in the lesson's custom color example?
plot accepts color with a name or a hex code such as #1f77b4.
Show answer
A — color="#1f77b4" — plot accepts color with a name or a hex code such as #1f77b4.
Which color guideline does the lesson give?
The tip adds that you should avoid using too many colors in one chart.
Show answer
A — Use high-contrast, colorblind-friendly colors and keep color meaning consistent — The tip adds that you should avoid using too many colors in one chart.
When are legends needed?
A legend tells the reader which line or marker belongs to which series, as with square and linear.
Show answer
A — When you plot multiple series — A legend tells the reader which line or marker belongs to which series, as with square and linear.
Next
Continue to Saving Plots as Images to export your finished, labelled charts.
🧪 Try It Yourself
Exercise 1 – Label a series and show the legend
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Use a hex color code
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Hide a series from the legend
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.