ใช้ ax.get_children() วนลูปหา Object ที่เป็น Instance ของ matplotlib.legend.Legend แล้วดึง .texts
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างข้อมูล และ Plot 2 เส้นพร้อม Label
- เพิ่ม Legend
- วนลูป Children ของ Axes หา Legend
- Print Legend Texts
- แสดงผล
ตัวอย่างโค้ด
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')
# ดึง Legends ทั้งหมด
for item in ax.get_children():
if isinstance(item, matplotlib.legend.Legend):
print(item.texts)
# item.texts คือ List ของ Text Objects
for text in item.texts:
print(f" Legend text: {text.get_text()}")
plt.show()
วิธีง่ายกว่า: ใช้ ax.get_legend()
legend = ax.get_legend()
if legend:
for text in legend.get_texts():
print(text.get_text())
# หรือเข้าถึง Handles
for handle, label in zip(legend.legend_handles, legend.get_texts()):
print(f"Handle: {handle}, Label: {label.get_text()}")
ผลลัพธ์
กราฟ Sin และ Cos พร้อม Legend ขวาบน Console แสดง Legend Texts: ["y=sin(x)", "y=cos(x)"]