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

การพลอต Animated Quivers ใน Python ด้วย Matplotlib


เพื่อทำ Animation Quivers (เวกเตอร์/ลูกศร) ใน Python

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • สร้าง x, y ด้วย numpy
  • สร้าง u, v ด้วย numpy
  • สร้าง figure และ subplots
  • พลอต 2D field ของลูกศรด้วย quiver()
  • ทำ animation โดยเปลี่ยนค่า u, v ใน animate() อัปเดตค่าและสี
  • แสดงรูปด้วย show()

ตัวอย่าง

import numpy as np
import random as rd
from matplotlib import pyplot as plt, animation

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

x, y = np.mgrid[:2 * np.pi:10j, :2 * np.pi:5j]
u = np.cos(x)
v = np.sin(y)

fig, ax = plt.subplots(1, 1)
qr = ax.quiver(x, y, u, v, color='red')

def animate(num, qr, x, y):
    u = np.cos(x + num * 0.1)
    v = np.sin(y + num * 0.1)
    qr.set_UVC(u, v)
    qr.set_color((rd.random(), rd.random(), rd.random(), rd.random()))
    return qr,

anim = animation.FuncAnimation(fig, animate, fargs=(qr, x, y), interval=50, blit=False)
plt.show()

ผลลัพธ์

การพลอต Animated Quivers ใน Python ด้วย Matplotlib