Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đặt tiêu đề cho nhóm marker cùng nhãn trong legend Matplotlib

Để đặ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 x bằng Numpy
  • Tạo 4 đường cong c1, c2, c3, c4 bằng plot()
  • Đặ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).

Đặt tiêu đề cho nhóm marker cùng nhãn trong legend Matplotlib

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.