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

การเปลี่ยนขนาดและตำแหน่ง subplot หลังสร้าง axes แล้วใน Matplotlib


ปรับขนาด/ตำแหน่ง subplot หลังสร้าง axes

ใช้ GridSpec จัดการ layout และเปลี่ยนตำแหน่ง axes หลังสร้างแล้ว

ขั้นตอน

  1. สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่ด้วย figure()
  2. เพิ่ม axes เข้า figure ด้วย add_subplot()
  3. ใช้ GridSpec() สร้าง grid layout
  4. ตั้งค่าตำแหน่งของ grid specs
  5. ตั้งค่า subplotspec instance
  6. เพิ่ม axes ใหม่ด้วย add_subplot() พร้อม gridspec instance
  7. ปรับ padding ระหว่าง subplots
  8. แสดงด้วย show()

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

from matplotlib import pyplot as plt
from matplotlib import gridspec as gridspec

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

fig = plt.figure()
ax = fig.add_subplot(111)
gs = gridspec.GridSpec(3, 1)

ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2])
fig.add_subplot(gs[2])

fig.tight_layout()
plt.show()

ผลลัพธ์

การเปลี่ยนขนาดและตำแหน่ง subplot หลังสร้าง axes แล้วใน Matplotlib