Để thêm tiêu đề (title) cho các hàng (rows) trong legend Matplotlib:
- Thiết lập kích thước figure và padding
- Tạo dữ liệu
ybằng numpy - Tạo list
markersvàlabels - Tạo figure và subplots
- Vẽ các đường với marker và label khác nhau
- Lấy handles và labels cho một nửa plot
- Tạo placeholder handles cho tiêu đề hàng
- Đặt legend trên plot
- Hiển thị bằng
show()
Ví dụ mã nguồn
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.exp(-np.arange(5))
markers = ["s", "o", "*"]
labels = ["one", "two"]
fig, ax = plt.subplots()
for i in range(6):
ax.plot(y * i + i / 2., marker=markers[i // 2], label=labels[i % 2])
h, l = ax.get_legend_handles_labels()
ph = [plt.plot([], marker="", ls="")[0]] * 2
handles = ph + h
labels = ["Title 1:", "Title 2:"] + l
plt.legend(handles, labels, ncol=4)
plt.show()
Kết quả
Legend 4 cột: 2 cột đầu là "Title 1:", "Title 2:" (placeholder rỗng), 2 cột sau là các marker thực tế.

Kỹ thuật: Tạo artist rỗng (plot([], marker="", ls="")[0]) làm placeholder cho tiêu đề hàng.