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

การสร้าง Function ที่ Return Figure ใน Matplotlib

ออกแบบ Function ที่สร้างและ Return Figure Object เพื่อให้สามารถนำไปใช้ต่อหรือบันทึกได้

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล X, Y
  3. สร้าง Function plot(x, y) ที่ Return fig
  4. เรียก Function และเก็บ Figure
  5. แสดงผล

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


import numpy as np
from matplotlib import pyplot as plt

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

def plot(x, y):
    fig = plt.figure()
    plt.plot(x, y)
    return fig

x = np.linspace(-10, 10, 100)
y = np.sin(x)

f = plot(x, y)
plt.show()

# สามารถบันทึกได้: f.savefig('plot.png')

รูปแบบที่แนะนำ (Object-Oriented)


def create_plot(x, y):
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_title('My Plot')
    return fig

fig = create_plot(x, y)
fig.savefig('my_plot.png', dpi=300)
plt.show()

ข้อดีของการ Return Figure

  • แยก Logic การสร้าง Plot ออกจากการแสดงผล
  • สามารถบันทึกไฟล์ได้หลายรูปแบบ/หลายที่
  • ง่ายต่อการ Test และ Reuse
  • ควบคุม Lifecycle ของ Figure ได้ชัดเจน

ผลลัพธ์

กราฟ Sin Wave แสดงในหน้าต่าง และมี Figure Object พร้อมใช้งานต่อ