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

วิธีวาด Animated Image Matrix ใน Matplotlib

สร้างแอนิเมชันเมทริกซ์ภาพ 6x6 ที่สุ่มค่าใหม่ทุกเฟรม

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Figure และ Subplots
  3. สร้างฟังก์ชัน update(i) สร้างเมทริกซ์สุ่มใหม่และ imshow()
  4. ปิดแกนด้วย set_axis_off()
  5. ใช้ FuncAnimation เรียก update ซ้ำ
  6. แสดงผล

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

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

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

def update(i):
    im_normed = np.random.rand(6, 6)
    ax.imshow(im_normed)
    ax.set_axis_off()

anim = FuncAnimation(fig, update, frames=20, interval=50)
plt.show()

ผลลัพธ์

แอนิเมชันเมทริกซ์ 6x6 สุ่มสีเปลี่ยนทุก 50ms

วิธีวาด Animated Image Matrix ใน Matplotlib