Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีดึงรายการ Axes ของ Figure ใน Pyplot

การเข้าถึงรายการ Axes ทั้งหมดใน Figure สามารถทำได้ด้วยเมธอด fig.get_axes() ซึ่งคืนค่ารายการของ Axes objects ทั้งหมดที่อยู่ใน Figure นั้น

ขั้นตอนการทำงาน

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูล X และ Y
  3. สร้าง Figure ด้วย plt.figure()
  4. เพิ่ม Subplot ด้วย fig.add_subplot(111) (1แถว 1คอลัมน์ index 1)
  5. ดึงรายการ Axes ด้วย fig.get_axes() และตั้งค่า label
  6. พลอตข้อมูลและแสดงผล

ตัวอย่างโค้ด

import numpy as np
from matplotlib import pyplot as plt

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

xs = np.linspace(1, 10, 10)
ys = np.tan(xs)

fig = plt.figure()
ax = fig.add_subplot(111)

# เข้าถึง axes แรก (index 0) และตั้งค่า label
fig.get_axes()[0].set_ylabel("Y-Axis")
fig.get_axes()[0].set_xlabel("X-Axis")

ax.plot(xs, ys, c='red')
plt.show()

การใช้งาน fig.get_axes()

  • คืนค่า list ของ Axes objects ทั้งหมดใน Figure
  • ลำดับตามที่สร้าง (creation order)
  • ใช้ได้กับ Figure ที่สร้างจาก plt.figure(), plt.subplots(), หรือ plt.subplot()

ตัวอย่าง: วนลูปตั้งค่า Axes ทั้งหมด


fig, axes = plt.subplots(2, 3, figsize=(12, 8))

# วนลูปผ่าน get_axes()
for i, ax in enumerate(fig.get_axes()):
    ax.set_title(f"Subplot {i+1}")
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.plot(np.random.rand(10))

plt.tight_layout()
plt.show()

ความแตกต่าง: fig.axes vs fig.get_axes()

  • fig.axes - property (attribute) คืนค่ารายการ axes เดียวกัน
  • fig.get_axes() - method คืนค่ารายการ axes เดียวกัน
  • ทั้งคู่เทียบเท่ากัน ใช้ตัวไหนก็ได้

การประยุกต์ใช้

เหมาะสำหรับการปรับแต่ง Figure ที่ซับซ้อนหลาย Subplots การวนลูปตั้งค่าร่วมกัน การสร้างฟังก์ชันจัดการ Figure แบบ generic หรือการ debug ดูว่ามี Axes ทั้งหมดกี่ตัว