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

ความหมายและการใช้งาน axes.flat ใน Matplotlib

axes.flat เป็น iterator แบบ 1 มิติที่วนลูปผ่านทุกอาเรย์ของ Axes ใน grid ซับพลอต (เช่น 2x3 = 6 axes) ทำให้เขียนโค้ดพลอตซ้ำได้สะดวกกว่าการเข้าถึงแบบ 2 มิติ axes[i, j]

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

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้างซับพลอต grid ด้วย plt.subplots(nrows=2, ncols=3)
  3. สร้างข้อมูล x, y
  4. วนลูปด้วย for ax in axes.flat: พลอตบนทุก axes
  5. แสดงผล

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

import numpy as np
from matplotlib import pyplot as plt

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

fig, axes = plt.subplots(nrows=2, ncols=3)
x = np.random.rand(10)
y = np.random.rand(10)

for ax in axes.flat:
    ax.plot(x, y)

plt.show()

ผลลัพธ์

ความหมายและการใช้งาน axes.flat ใน Matplotlib