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

Vẽ nhiều legend trên cùng một axes Matplotlib

Để hiển thị nhiều legend riêng biệt trên cùng một axes, ta tạo legend đầu tiên, thêm nó như artist vào axes, rồi tạo legend thứ hai.

Các bước

  • Thiết lập figure size và autolayout.
  • Vẽ 2 đường với label, linestyle, linewidth khác nhau.
  • Tạo legend đầu tiên cho line1 tại loc='upper right'.
  • Thêm artist legend đầu tiên vào axes: plt.gca().add_artist(first_legend).
  • Tạo legend thứ hai cho line2 tại loc='lower right'.
  • Hiển thị bằng show().

Ví dụ

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)
first_legend = plt.legend(handles=[line1], loc='upper right')
plt.gca().add_artist(first_legend)
plt.legend(handles=[line2], loc='lower right')
plt.show()

Kết quả

Vẽ nhiều legend trên cùng một axes Matplotlib