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

Cách điều chỉnh kích thước hộp legend trong Matplotlib

Dùng borderpad trong legend() để tăng khoảng đệm quanh legend box.

  • Vẽ line1, line2 với linewidth khác nhau.
  • plt.legend([line1, line2], ["line1", "line2"], bbox_to_anchor=(0.35, 1.0), borderpad=2).
  • show().

Ví dụ

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
line1, = plt.plot([1, 5, 1, 7], linewidth=0.7)
line2, = plt.plot([5, 1, 7, 1], linewidth=2.0)
plt.legend([line1, line2], ["line1", "line2"], bbox_to_anchor=(0.35, 1.0), borderpad=2)
plt.show()

Kết quả

Legend box lớn hơn do borderpad=2, nằm ở vị trí (0.35, 1.0).