Skip to content

Legends and Colors

Legends

Legends are needed when you plot multiple series. McKinney is clear about one gotcha here: passing label="..."label="..." to plot()plot() doesn’t draw a legend by itself — you must still call ax.legend()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().
Legend
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()
Legend
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
Custom color
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()
Custom color
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.

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

Exercise 2 – Use a hex color code

Exercise 3 – Hide a series from the legend

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did