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

Hiển thị legend ngang (horizontal) trong Matplotlib

Để sắp xếp các mục legend theo hàng ngang, đặt tham số ncol (số cột) trong plt.legend().

Các bước

  • Thiết lập figure size và autolayout.
  • Vẽ 3 đường với label line1, line2, line3.
  • Gọi plt.legend(ncol=3, loc="upper 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="line1")
line2, = plt.plot([3, 2, 1], label="line2")
line3, = plt.plot([2, 3, 1], label="line3")
plt.legend(ncol=3, loc="upper right")
plt.show()

Kết quả

Hiển thị legend ngang (horizontal) trong Matplotlib