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

วิธีแสดง Axes Subplot ใน Python Matplotlib

การแสดง Subplot ใน Matplotlib ทำได้โดยใช้ plt.show() หลังจากสร้าง Axes และพลอตข้อมูลแล้ว เมื่อสร้าง Figure หลายอัน plt.show() จะแสดงทั้งหมดพร้อมกัน

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

  1. นำเข้า matplotlib.pyplot และ numpy
  2. สร้างข้อมูล X และ Y (ตัวอย่าง: x = np.arange(10), y = np.exp(x))
  3. พลอตข้อมูลด้วย plt.plot(x, y)
  4. แสดงผลด้วย plt.show()

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

from matplotlib import pyplot as plt
import numpy as np

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

x = np.arange(10)
y = np.exp(x)
plt.plot(x, y)
plt.show()

การสร้าง Subplot หลายตัว


# วิธี 1: plt.subplot(nrows, ncols, index)
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, -y)
# ...

# วิธี 2: plt.subplots() - แนะนำสำหรับการควบคุมที่ดีกว่า
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes[0, 0].plot(x, y)
axes[0, 1].plot(x, -y)
axes[1, 0].scatter(x, y)
axes[1, 1].bar(x, y)
plt.tight_layout()
plt.show()

คำอธิบาย plt.subplots()

พารามิเตอร์คำอธิบาย
nrows, ncolsจำนวนแถวและคอลัมน์ของ subplot grid
figsizeขนาด Figure (นิ้ว)
sharex, shareyใช้แกน X/Y ร่วมกันระหว่าง subplots
squeeze=Trueคืนค่า axes เป็นอาร์เรย์ 2D เสมอ

การเข้าถึง Axes แต่ละตัว

  • axes[0, 0] - แถวบน ซ้าย
  • axes[0, 1] - แถวบน ขวา
  • axes.flat - iterator ทุก axes
  • fig.get_axes() - รายการ axes ทั้งหมดใน figure

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

เหมาะสำหรับการเปรียบเทียบกราฟหลายกราฟ ด้านข้างกัน การสร้างแดชบอร์ด การแสดงผลลัพธ์หลายมุมมอง หรือการจัดหน้ารายงาน