การทำ Animation หลาย Plots พร้อมกันด้วย For Loop
รวม Line2D objects และ Bar patches ใน list เดียว แล้วอัปเดตใน animate()
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- สร้าง figure และ axes กำหนด xlim, ylim
- สร้างหลายเส้น (lines) และแท่ง (rectangles)
- รวมเป็น list patches
- ใน animate() ใช้ for loop อัปเดตข้อมูลแต่ละ line และ rectangle
- คืนค่า patches สำหรับ blitting
- สร้าง FuncAnimation และแสดงผล
ตัวอย่างโค้ด
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))
N = 4
x = np.linspace(-5, 5, 100)
lines = [plt.plot(x, np.sin(x))[0] for _ in range(N)]
rectangles = plt.bar([0.5, 1, 1.5], [50, 40, 90], width=0.1)
patches = lines + list(rectangles)
def animate(i):
for j, line in enumerate(lines):
line.set_data([0, 2, i, j], [0, 3, 10 * j, i])
for j, rectangle in enumerate(rectangles):
rectangle.set_height(i / (j + 1))
return patches
anim = animation.FuncAnimation(fig, animate, frames=100, interval=20, blit=True)
plt.show()
คำอธิบาย
blit=True ต้องการคืนค่า sequence ของ artists ที่เปลี่ยนแปลง (patches)