Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make two markers share the same label in the legend using Matplotlib?
To make two markers share the same label in the legend using Matplotlib, you can assign the same label name to multiple plot elements. When Matplotlib encounters duplicate labels, it automatically groups them under a single legend entry.
Basic Example with Shared Labels
Here's how to create two different plots that share the same legend label ?
import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-5, 5, 100) plt.plot(x, np.sin(x), ls="dotted", label='y=f(x)') plt.plot(x, np.cos(x), ls="-", label='y=f(x)') plt.legend(loc=1) plt.show()
In this example, both the sine and cosine curves share the label 'y=f(x)' in the legend, creating a single legend entry.
Practical Use Case with Scatter and Line Plots
A more practical example where you might want shared labels is when combining scatter points with trend lines ?
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y1 = np.array([2, 4, 1, 5, 3])
y2 = np.array([1, 3, 2, 4, 5])
# Plot scatter points and lines with shared labels
plt.scatter(x, y1, color='blue', label='Dataset A')
plt.plot(x, y1, color='blue', linestyle='--', label='Dataset A')
plt.scatter(x, y2, color='red', label='Dataset B')
plt.plot(x, y2, color='red', linestyle='--', label='Dataset B')
plt.legend()
plt.title('Scatter Points with Trend Lines')
plt.show()
This creates a cleaner legend where each dataset appears only once, even though both scatter points and lines are plotted.
Alternative Approach Using _nolegend_
You can also explicitly control which elements appear in the legend by using the special label '_nolegend_' ?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 50)
plt.plot(x, np.sin(x), 'b-', label='Trigonometric Functions')
plt.plot(x, np.cos(x), 'r-', label='_nolegend_')
plt.plot(x, np.tan(x), 'g--', label='_nolegend_')
plt.ylim(-2, 2)
plt.legend()
plt.title('Multiple Functions with Single Legend Entry')
plt.show()
This approach gives you more explicit control over which plots contribute to the legend.
Best Practices
| Approach | Use Case | Advantage |
|---|---|---|
| Same label names | Related data series | Automatic grouping |
| _nolegend_ label | Auxiliary plot elements | Explicit control |
| Manual legend creation | Complex customization | Full control |
Conclusion
While sharing legend labels can reduce clutter, use this technique sparingly and only when plots are genuinely related. For most cases, distinct labels provide better clarity and help readers understand your visualization.
