การสร้าง Animation ด้วย FuncAnimation
ใช้ FuncAnimation เพื่ออัปเดตข้อมูลแบบ real-time บน subplots
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- สร้าง figure และ subplots
- สร้างฟังก์ชัน init() สำหรับ clear frame
- ใช้ FuncAnimation เรียกฟังก์ชัน animate ซ้ำๆ
- กำหนดฟังก์ชัน animate อัปเดตข้อมูลใน Line2D object
- แสดงผลด้วย show()
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r*')
def init():
ax.set_xlim(0, 100)
ax.set_ylim(-1, 1)
return ln,
def animate(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, animate, init_func=init, blit=True, frames=100)
plt.show()
คำอธิบาย
- blit=True: อัปเดตเฉพาะส่วนที่เปลี่ยนแปลง (เร็วกว่า)
- frames=100: จำนวนเฟรมทั้งหมด
- init_func: ฟังก์ชันเริ่มต้นตั้งค่า axes limits