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

วิธีใช้ matplotlib.animate สร้างแอนิเมชัน contour plot ใน Python


สร้างแอนิเมชัน contour plot

ใช้ FuncAnimation อัปเดต contour plot ซ้ำๆ

ขั้นตอน

  1. สร้างข้อมูลสุ่มขนาด 10x10x8
  2. สร้าง figure และ subplots ด้วย subplots()
  3. ใช้ FuncAnimation() เรียกฟังก์ชัน animate ซ้ำ
  4. กำหนดฟังก์ชัน animate อัปเดตค่า contour
  5. แสดงด้วย show()

ตัวอย่างโค้ด

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams["figure.figsize"] = [7.00, 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])

ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False)
plt.show()

ผลลัพธ์

วิธีใช้ matplotlib.animate สร้างแอนิเมชัน contour plot ใน Python