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

Matplotlib - ความแตกต่างระหว่าง plt.subplots() และ plt.figure()

plt.figure() — สร้าง Figure ใหม่ หรือ เปิดใช้งาน Figure ที่มีอยู่แล้ว

plt.subplots() — สร้าง Figure พร้อมชุด Subplots (Axes) พร้อมกัน

ตัวอย่างเปรียบเทียบ

from matplotlib import pyplot as plt

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

# ใช้ plt.figure()
fig1 = plt.figure("Figure 1 - plt.figure")

# ใช้ plt.subplots()
fig2, ax = plt.subplots()
plt.title("Figure 2 - plt.subplots")

plt.show()

ผลลัพธ์

plt.figure() สร้าง Figure ว่างเปล่า

Matplotlib - ความแตกต่างระหว่าง plt.subplots() และ plt.figure()

plt.subplots() สร้าง Figure พร้อม Axes พร้อมใช้งาน

Matplotlib - ความแตกต่างระหว่าง plt.subplots() และ plt.figure()

สรุป

  • plt.figure() ใช้เมื่อต้องการควบคุม Figure แบบ Manual
  • plt.subplots() ใช้เมื่อต้องการหลาย Subplots หรือต้องการ Axes ทันที