ใช้ plt.GridSpec และ update() เพื่อควบคุมระยะห่างระหว่าง Subplots (wspace, hspace) อย่างละเอียด
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง GridSpec Layout
- ปรับ wspace (แนวนอน) และ hspace (แนวตั้ง)
- เพิ่ม Subplots ตาม Grid
- แสดงผล
ตัวอย่างโค้ด
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# สร้าง Grid 2x2
ax = plt.GridSpec(2, 2)
# ปรับระยะห่าง: wspace=แนวนอน, hspace=แนวตั้ง
ax.update(wspace=0.5, hspace=0.5)
# วาง Subplots ตาม Grid
ax1 = plt.subplot(ax[0, :]) # แถวแรก ทั้ง 2 คอลัมน์
ax2 = plt.subplot(ax[1, 0]) # แถวที่สอง คอลัมน์แรก
ax3 = plt.subplot(ax[1, 1]) # แถวที่สอง คอลัมน์ที่สอง
plt.show()
วิธีอื่น: ใช้ subplots_adjust
fig, axes = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.5, hspace=0.5)
การใช้ constrained_layout (Matplotlib 3.1+)
fig, axes = plt.subplots(2, 2, constrained_layout=True)
# ปรับ spacing อัตโนมัติ
ผลลัพธ์
Layout 2x2 ที่มีระยะห่างระหว่าง Subplots กว้างขึ้น (wspace=0.5, hspace=0.5) ทำให้ไม่ทับซ้อนกัน