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

วิธีสร้างแอนิเมชันกราฟเส้นใน Matplotlib

การสร้างแอนิเมชันใน Matplotlib ใช้โมดูล matplotlib.animation โดยเฉพาะคลาส FuncAnimation ที่เรียกฟังก์ชันอัปเดตข้อมูลซ้ำๆ ตามช่วงเวลา (interval) ที่กำหนด

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

  1. นำเข้า numpy, matplotlib.pyplot, และ matplotlib.animation
  2. สร้าง Figure และ Axes ด้วย plt.subplots()
  3. กำหนดขอบเขตแกน X และ Y ด้วย ax.set(xlim=..., ylim=...)
  4. สร้างข้อมูลกริด 2 มิติสำหรับแอนิเมชันด้วย np.meshgrid()
  5. คำนวณข้อมูลเฟรมทั้งหมดล่วงหน้า (pre-compute) เพื่อประสิทธิภาพ
  6. พลอตเส้นเริ่มต้นด้วย ax.plot() และเก็บออบเจกต์ Line2D ไว้ในตัวแปร (เช่น line, = ax.plot(...))
  7. สร้างฟังก์ชัน animate(i) ที่อัปเดตข้อมูล Y ของเส้นด้วย line.set_ydata()
  8. สร้างแอนิเมชันด้วย animation.FuncAnimation(fig, animate, interval=100, frames=len(t)-1)
  9. (ตัวเลือก) บันทึกเป็น GIF ด้วย anim.save('filename.gif')
  10. แสดงผลด้วย 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

พารามิเตอร์คำอธิบาย
figFigure 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) การจำลองฟิสิกส์ การแสดงคลื่น และการสร้างเนื้อหาการศึกษาแบบโต้ตอบ