Python
Data Visualization
Matplotlib
Legends
Plotting

Remove duplicate legend entries in Matplotlib

Codemia Knowledge Hub ·

Matplotlib creates one legend entry per labeled plotting call, so repeated series produce duplicate legend markers. To show each entry once, either suppress repeated labels while plotting or deduplicate the handles from get_legend_handles_labels() before calling legend().

Label only the first occurrence with _nolegend_

The cleanest approach is to assign the real label only the first time a category is plotted. Later calls for the same category use the reserved label "_nolegend_", which tells Matplotlib to skip that artist when building the legend.

python
1import matplotlib.pyplot as plt
2
3points = [
4    ("A", 1, 2),
5    ("A", 2, 3),
6    ("B", 1, 1),
7    ("B", 2, 2),
8    ("C", 3, 2),
9]
10
11seen = set()
12
13fig, ax = plt.subplots()
14
15for group, x, y in points:
16    label = group if group not in seen else "_nolegend_"
17    seen.add(group)
18    ax.scatter(x, y, label=label, s=100)
19
20ax.legend(title="Group")
21ax.set_xlabel("X")
22ax.set_ylabel("Y")
23ax.set_title("Legend entries appear once")
24plt.show()

This never builds the duplicate entries in the first place, which makes it a good fit for loops where you learn the categories as you iterate.

Deduplicate with get_legend_handles_labels()

When you do not control the plotting loop, or several helper functions add labels independently, read the axis handles and labels and keep only the first occurrence of each label.

python
1import matplotlib.pyplot as plt
2
3fig, ax = plt.subplots()
4
5ax.plot([0, 1, 2], [1, 2, 3], marker="o", label="Training")
6ax.plot([0, 1, 2], [1.5, 2.5, 3.5], marker="o", label="Training")
7ax.plot([0, 1, 2], [0.5, 1.5, 2.5], marker="s", label="Validation")
8
9handles, labels = ax.get_legend_handles_labels()
10
11unique = {}
12for handle, label in zip(handles, labels):
13    if label not in unique:
14        unique[label] = handle
15
16ax.legend(unique.values(), unique.keys(), title="Series")
17ax.set_title("Deduplicated legend")
18plt.show()

Python dictionaries preserve insertion order, so the first instance of each label is the one that stays in the legend.

Which approach to use

Suppress labels during plotting when:

  • You are already plotting in a loop.
  • You want the simplest and cheapest legend creation.
  • You know exactly which series should appear once.

Deduplicate after plotting when:

  • Multiple functions contribute artists.
  • You cannot easily control the original labels.
  • You need to clean up the legend right before display.

The two also combine well: suppress obvious duplicates in the main loop, then run a final deduplication pass in a reporting utility for safety.

Keeping a dense legend readable

If many series share similar colors or markers, consider increasing the legend marker size, moving the legend outside the axes, or adding a title.

For scatter plots, the legend handle is not always identical to the series on the chart. That is normal: the legend is a compact summary, not a second copy of the plot. Focus on keeping labels unique and visually distinct.

With custom artists or collections, get_legend_handles_labels() still works in many cases, but heavily customized legends may need manual handles.

Mistakes that bring duplicates back

  • Calling ax.legend() repeatedly inside a loop. That rebuilds the legend over and over and often still leaves duplicates behind.
  • Giving slightly different labels to the same series, such as "Training" and "training". Labels are matched exactly, so these become separate entries.
  • Treating the legend as the whole fix. Duplicate labels usually mean duplicate labeled artists, and cleaning the legend does not change the plot objects. If the chart itself is cluttered, simplify the plotting logic too.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design