การแสดง Subplot ใน Matplotlib ทำได้โดยใช้ plt.show() หลังจากสร้าง Axes และพลอตข้อมูลแล้ว เมื่อสร้าง Figure หลายอัน plt.show() จะแสดงทั้งหมดพร้อมกัน
ขั้นตอนการทำงาน
- นำเข้า
matplotlib.pyplotและnumpy - สร้างข้อมูล X และ Y (ตัวอย่าง:
x = np.arange(10),y = np.exp(x)) - พลอตข้อมูลด้วย
plt.plot(x, y) - แสดงผลด้วย
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 ทุก axesfig.get_axes()- รายการ axes ทั้งหมดใน figure
การประยุกต์ใช้
เหมาะสำหรับการเปรียบเทียบกราฟหลายกราฟ ด้านข้างกัน การสร้างแดชบอร์ด การแสดงผลลัพธ์หลายมุมมอง หรือการจัดหน้ารายงาน