สร้างอนิเมชันของกราฟเส้นระดับ (contour plot)
ขั้นตอนการทำงาน
- กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
- สร้างข้อมูลสุ่มขนาด 10x10
- สร้าง figure และชุด subplots ด้วย subplots()
- สร้างอนิเมชันโดยเรียกฟังก์ชัน func ซ้ำด้วยคลาส FuncAnimation()
- กำหนดเมธอด animate() เพื่ออัปเดตค่า contour ใช้ใน FuncAnimation()
- ใช้เมธอด show() เพื่อแสดงรูปภาพ
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()
def animate(i):
ax.clear()
ax.contourf(data[:, :, i], cmap="copper")
ani = animation.FuncAnimation(fig, animate, 5, interval=100, blit=False)
plt.show()
ผลลัพธ์
