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

Khắc phục Matplotlib animation không chạy trên IPython Notebook

Để tạo animation hoạt động trong Jupyter/IPython Notebook, dùng FuncAnimation với các thiết lập phù hợp.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu ngẫu nhiên 3D (frames).
  • Tạo figure, axes.
  • Định nghĩa hàm animate(i) cập nhật contour.
  • Tạo FuncAnimation với blit=False (thường cần thiết cho notebook).
  • Hiển thị bằng show() (hoặc dùng HTML(ani.to_jshtml()) trong notebook).

Ví dụ

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

plt.rcParams["figure.figsize"] = [7.50, 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ả

Khắc phục Matplotlib animation không chạy trên IPython Notebook