How to set a title above each marker which represents a same label in Matplotlib?

To set a title above each marker which represents the same label in Matplotlib, you can group multiple plot lines under the same legend label. This is useful when you have variations of the same function or data series that should be grouped together in the legend.

Steps to Group Markers by Label

  • Set the figure size and adjust the padding between and around the subplots.

  • Create x data points using NumPy.

  • Create multiple curves using plot() method with the same label.

  • Use HandlerTuple to group markers with identical labels together.

  • Place a legend on the figure to display grouped markers.

  • Display the figure using show() method.

Example

Here's how to create grouped legend entries for sine and cosine functions ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import legend_handler

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create x data points
x = np.linspace(-10, 10, 100)

# Create four curves with same labels for grouping
c1, = plt.plot(x, np.sin(x), ls='dashed', label='y=sin(x)')
c2, = plt.plot(x, np.sin(x+0.25), ls='dashdot', label='y=sin(x)')
c3, = plt.plot(x, np.cos(x), ls='solid', label='y=cos(x)')
c4, = plt.plot(x, np.cos(x+0.25), ls=':', label='y=cos(x)')

# Group curves by label using HandlerTuple
plt.legend([(c1, c2), (c3, c4)], ['y=sin(x)', 'y=cos(x)'], 
           loc='upper right', 
           handler_map={tuple: legend_handler.HandlerTuple(ndivide=None)})

plt.title('Grouped Legend Markers Example')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True, alpha=0.3)
plt.show()

Output

y=sin(x) y=cos(x) Grouped Legend Markers Example x y

How It Works

The HandlerTuple class allows you to group multiple plot objects under a single legend entry. By passing tuples of plot objects to the legend function, you can display multiple line styles or markers under one label title.

Key Parameters

  • ndivide=None: Controls spacing between grouped markers in the legend

  • handler_map: Maps tuple objects to the HandlerTuple handler

  • loc: Position of the legend ('upper right', 'lower left', etc.)

Conclusion

Use HandlerTuple with grouped plot objects to create organized legends where multiple variations of the same data series appear under a single title. This approach keeps legends clean and meaningful when dealing with related datasets.

Updated on: 2026-03-26T00:28:23+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements