การสร้างแอนิเมชันใน Matplotlib ใช้โมดูล matplotlib.animation โดยเฉพาะคลาส FuncAnimation ที่เรียกฟังก์ชันอัปเดตข้อมูลซ้ำๆ ตามช่วงเวลา (interval) ที่กำหนด
ขั้นตอนการทำงาน
- นำเข้า
numpy,matplotlib.pyplot, และmatplotlib.animation - สร้าง Figure และ Axes ด้วย
plt.subplots() - กำหนดขอบเขตแกน X และ Y ด้วย
ax.set(xlim=..., ylim=...) - สร้างข้อมูลกริด 2 มิติสำหรับแอนิเมชันด้วย
np.meshgrid() - คำนวณข้อมูลเฟรมทั้งหมดล่วงหน้า (pre-compute) เพื่อประสิทธิภาพ
- พลอตเส้นเริ่มต้นด้วย
ax.plot()และเก็บออบเจกต์ Line2D ไว้ในตัวแปร (เช่นline, = ax.plot(...)) - สร้างฟังก์ชัน
animate(i)ที่อัปเดตข้อมูล Y ของเส้นด้วยline.set_ydata() - สร้างแอนิเมชันด้วย
animation.FuncAnimation(fig, animate, interval=100, frames=len(t)-1) - (ตัวเลือก) บันทึกเป็น GIF ด้วย
anim.save('filename.gif') - แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.set(xlim=(-3, 3), ylim=(-1, 1))
x = np.linspace(-3, 3, 91)
t = np.linspace(1, 25, 30)
X2, T2 = np.meshgrid(x, t)
sinT2 = np.sin(2 * np.pi * T2 / T2.max())
F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2))
line, = ax.plot(x, F[0, :], color='k', lw=2)
def animate(i):
line.set_ydata(F[i, :])
anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)
anim.save('503.gif')
plt.show()
คำอธิบายพารามิเตอร์ FuncAnimation
| พารามิเตอร์ | คำอธิบาย |
|---|---|
fig | Figure object ที่จะทำแอนิเมชัน |
animate | ฟังก์ชัน callback ที่รับ frame index (i) |
interval | ช่วงเวลาระหว่างเฟรม (มิลลิวินาที) |
frames | จำนวนเฟรมทั้งหมด หรือ iterable ของ frame indices |
blit=True | เพิ่มประสิทธิภาพโดยวาดเฉพาะส่วนที่เปลี่ยนแปลง |
repeat=True | เล่นซ้ำเมื่อจบ |
เคล็ดลับเพื่อประสิทธิภาพ
- คำนวณข้อมูลทั้งหมดล่วงหน้า (pre-compute) อย่าคำนวณในฟังก์ชัน animate
- ใช้
blit=Trueและ return tuple ของ artists ที่เปลี่ยนแปลงใน animate() - สำหรับบันทึกวิดีโอ ใช้
writer='ffmpeg'หรือ'pillow'สำหรับ GIF - ใน Jupyter Notebook ใช้
%matplotlib notebookหรือfrom IPython.display import HTML; HTML(anim.to_jshtml())
การประยุกต์ใช้
เหมาะสำหรับการแสดงข้อมูลอนุกรมเวลา (time series) การจำลองฟิสิกส์ การแสดงคลื่น และการสร้างเนื้อหาการศึกษาแบบโต้ตอบ