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

Cách dùng matplotlib.animate để tạo animation contour plot trong Python

Tạo animation contourf bằng FuncAnimation.

  • Tạo data shape (10,10,8) ngẫu nhiên.
  • fig, ax = subplots().
  • Định nghĩa animate(i): ax.clear(), ax.contourf(data[:,:,i]).
  • ani = animation.FuncAnimation(fig, animate, 5, interval=50, blit=False).
  • show().

Ví dụ

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

Kết quả

Animation contourf thay đổi qua 5 frames, lưu thành GIF nếu cần.