เพื่อพลอต Grid ข้ามหลาย subplots ใน Matplotlib สร้างหลาย subplots แล้วตั้งค่า spine visibility เป็น false บนแกนบางอัน
ขั้นตอน
- ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
- สร้าง figure และ subplots ด้วย subplots()
- เพิ่ม subplot และตั้ง spine visibility เป็น false
- ปิดป้ายแกน ax3
- Share แกน X ตามที่ต้องการ
- ตั้งค่า grid lines สำหรับ ax1, ax2, ax3
- แสดงรูปด้วย show()
ตัวอย่าง
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2) = plt.subplots(nrows=2)
ax3 = fig.add_subplot(111, zorder=-1)
for _, spine in ax3.spines.items():
spine.set_visible(False)
ax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False)
ax3.get_shared_x_axes().join(ax3, ax1)
ax3.grid(axis="x")
ax1.grid()
ax2.grid()
plt.show()ผลลัพธ์
