Để đặt tiêu đề (title) cho nhóm marker đại diện cho cùng một nhãn trong legend Matplotlib:
- Thiết lập kích thước figure và padding
- Tạo dữ liệu
xbằng Numpy - Tạo 4 đường cong
c1, c2, c3, c4bằngplot() - Đặt legend gom nhóm marker cùng nhãn
- Hiển thị bằng
show()
Ví dụ mã nguồn
import numpy as np
from matplotlib import pyplot as plt, legend_handler
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
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)')
plt.legend([(c1, c2), (c3, c4)], ['y=sin(x)', 'y=cos(x)'],
loc='upper right',
handler_map={tuple: legend_handler.HandlerTuple(ndivide=None)})
plt.show()
Kết quả
Legend có 2 nhóm: "y=sin(x)" gom 2 marker (dashed, dashdot), "y=cos(x)" gom 2 marker (solid, dotted).

Giải thích: Truyền list of tuples cho handles, dùng HandlerTuple(ndivide=None) để hiển thị các marker cạnh nhau không chia cột.