Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo animation quiver (vector field) trong Python bằng Matplotlib


Các bước

  1. Thiết lập kích thước hình và padding.
  2. Tạo lưới x, y bằng numpy.
  3. Tạo thành phần vector u, v.
  4. Tạo figure và subplots.
  5. Vẽ trường vector bằng quiver().
  6. Trong hàm animate(), cập nhật u, v và màu vector.
  7. Tạo FuncAnimation.
  8. Gọi show().

Ví dụ

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()

Kết quả

Tạo animation quiver (vector field) trong Python bằng Matplotlib