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

การวาดขอบรอบ Subplots ใน Matplotlib


ใช้ Rectangle patch บน subplots เพื่อวาดขอบรอบ

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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • เพิ่ม subplot ลงใน figure ปัจจุบันด้วย subplot(121)
  • ดึงค่า axes ของ subplot
  • สร้างสี่เหลี่ยมผืนผ้าจากจุดล็อก (anchor point) xy พร้อม width และ height
  • เพิ่ม rectangle patch เข้าไปใน subplot ปัจจุบัน
  • ตั้งค่า clipping ของ artist
  • เพิ่ม subplot ที่สองด้วย subplot(122)
  • ตั้งชื่อเรื่องของ subplot ปัจจุบัน
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

from matplotlib import pyplot as plt

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

sub = plt.subplot(121)
ax = sub.axis()
rec = plt.Rectangle((ax[0] - 0.7, ax[2] - 0.2), (ax[1] - ax[0]) + 1, (ax[3] - ax[2]) + 0.4, fill=False, lw=2, linestyle="dotted")
rec = sub.add_patch(rec)
rec.set_clip_on(False)
plt.title("with border")
sub = plt.subplot(122)
plt.title("without border")
plt.show()

ผลลัพธ์

การวาดขอบรอบ Subplots ใน Matplotlib