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

การทำ Animation กับ Contour Plot ใน Matplotlib

สร้างแอนิเมชัน Contour Plot โดยอัปเดตข้อมูลทุกเฟรม

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูลสุ่ม 3D (10x10x8) สำหรับ Contour
  3. สร้าง Figure และ Subplots
  4. กำหนดฟังก์ชัน animate(i) ที่ล้าง Axes และวาด contourf ใหม่
  5. ใช้ FuncAnimation เรียกฟังก์ชันซ้ำ
  6. แสดงผลด้วย plt.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

# ข้อมูลสุ่ม 10x10x8
data = np.random.randn(800).reshape(10, 10, 8)

fig, ax = plt.subplots()

def animate(i):
    ax.clear()
    ax.contourf(data[:, :, i], cmap='plasma')

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

ผลลัพธ์

แอนิเมชัน Contour Plot ที่เปลี่ยนสีทุกเฟรม

การทำ Animation กับ Contour Plot ใน Matplotlib