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

การปรับระยะห่างระหว่าง Subplots ใน Matplotlib และ Seaborn

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

  • กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots

  • สร้าง Figure และชุด Subplots

  • ปรับพารามิเตอร์เลย์เอาต์ของ Subplot ด้วย subplots_adjust()

  • สร้าง Box Plot ของ Seaborn สำหรับทุก Subplot

  • แสดงรูปภาพด้วยเมธอด show()

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

import seaborn as sns
from matplotlib import pyplot as plt

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

fig, axes = plt.subplots(2, 2)

# ปรับระยะห่าง: hspace=แนวตั้ง, wspace=แนวนอน
fig.subplots_adjust(hspace=0.125, wspace=0.125)

# สร้าง Boxplot สำหรับทุก Subplot
sns.boxplot(ax=axes[0, 0])
sns.boxplot(ax=axes[0, 1])
sns.boxplot(ax=axes[1, 0])
sns.boxplot(ax=axes[1, 1])

plt.show()

ผลลัพธ์

กริด 2x2 ของ Boxplot ที่มีระยะห่างระหว่างกราฟเล็กลง (hspace=0.125, wspace=0.125) ทำให้เนื้อที่พล็อตใหญ่ขึ้น

พารามิเตอร์สำคัญ:

  • hspace - ระยะห่างแนวตั้งระหว่างแถว (0.0 - 1.0)
  • wspace - ระยะห่างแนวนอนระหว่างคอลัมน์ (0.0 - 1.0)
  • ยังสามารถใช้ left, right, top, bottom ควบคุมขอบรอบนอกได้