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

Lấy tất cả legend từ plot trong Matplotlib

Để lấy tất cả legend từ một plot trong Matplotlib, dùng phương thức get_children() để lấy tất cả thuộc tính của axes, sau đó lặp qua. Nếu item là instance của Legend, lấy texts của legend.

Các bước

  • Thiết lập kích thước figure và padding
  • Tạo dữ liệu x bằng numpy
  • Tạo figure và subplots
  • Vẽ sin(x) và cos(x) với label và color khác nhau
  • Lấy children của axis và lấy texts của legend
  • Hiển thị bằng show()

Ví dụ mã nguồn

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

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

x = np.linspace(-10, 10, 100)
fig, ax = plt.subplots()
ax.plot(np.sin(x), color='red', lw=7, label="y=sin(x)")
ax.plot(np.cos(x), color='orange', lw=7, label="y=cos(x)")
plt.legend(loc='upper right')
for item in ax.get_children():
    if isinstance(item, matplotlib.legend.Legend):
        print(item.texts)
plt.show()

Kết quả

Đồ thị sin/cos với legend. Console in ra list Text objects của legend: [, ].

Lấy tất cả legend từ plot trong Matplotlib

Cách khác: ax.get_legend().get_texts() trực tiếp nếu đã có legend.