Python Central HubSign in

Data Analytics with Python / Phase 5: Data Visualization with Matplotlib

Legends and Colors

Add legends for multiple series and use consistent, readable colors.

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.

diagram How a legend gets built mermaid
Each series' label, set at plot time, only becomes a visible legend once you call ax.legend().
Python
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
Python
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

quizCheck yourself
  1. You pass label="square" to plt.plot but never call plt.legend(). What appears?

    Show answer

    A — No legend, because labels alone do not draw one — You must call legend() afterwards, whether or not you set labels beforehand.

  2. Which color argument is used in the lesson's custom color example?

    Show answer

    A — color="#1f77b4" — plot accepts color with a name or a hex code such as #1f77b4.

  3. Which color guideline does the lesson give?

    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.

  4. When are legends needed?

    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

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Use a hex color code

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Hide a series from the legend

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did