โดยใช้เมธอด FuncAnimation เราสามารถสร้างภาพเคลื่อนไหว (animation) ได้ เราจะสร้างฟังก์ชันที่ผู้ใช้กำหนดเองชื่อ update เพื่อเปลี่ยนตำแหน่งของอนุภาค (particles) ตลอดเวลา และในที่สุดเมธอดจะคืนค่าอินสแตนซ์ของ scatter plot
ขั้นตอน
กำหนดตำแหน่งเริ่มต้น ความเร็ว แรง และขนาดของอนุภาค
สร้าง Figure ใหม่ หรือเปิดใช้งาน Figure ที่มีอยู่ด้วย
figsize=(7, 7)เพิ่มแกน (axes) ให้กับ Figure ปัจจุบัน และทำให้เป็นแกนปัจจุบัน พร้อมกำหนด
xlimและylimวาด scatter plot สำหรับตำแหน่งเริ่มต้นของอนุภาค
สร้างแอนิเมชันโดยการเรียกฟังก์ชัน
funcซ้ำๆ เราสามารถส่งฟังก์ชันที่ผู้ใช้กำหนดเองซึ่งช่วยเปลี่ยนตำแหน่งอนุภาค ให้กับคลาสFuncAnimationแสดงกราฟด้วย
plt.show()
ตัวอย่าง
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
dt = 0.005
n = 20
L = 1
particles = np.zeros(n, dtype=[("position", float, 2),
("velocity", float, 2),
("force", float, 2),
("size", float, 1)])
particles["position"] = np.random.uniform(0, L, (n, 2))
particles["velocity"] = np.zeros((n, 2))
particles["size"] = 0.5 * np.ones(n)
fig = plt.figure(figsize=(7, 7))
ax = plt.axes(xlim=(0, L), ylim=(0, L))
scatter = ax.scatter(particles["position"][:, 0], particles["position"][:, 1])
def update(frame_number):
particles["force"] = np.random.uniform(-2, 2., (n, 2))
particles["velocity"] = particles["velocity"] + particles["force"] * dt
particles["position"] = particles["position"] + particles["velocity"] * dt
particles["position"] = particles["position"] % L
scatter.set_offsets(particles["position"])
return scatter,
anim = FuncAnimation(fig, update, interval=10)
plt.show()
ผลลัพธ์
