1、定義方程
使用matplotlib做動畫也是可以的,我們使用其中一種方式,function animation來說說, 具體可參考matplotlib animation api。首先,我們做一些准備工作:
from matplotlib import pyplot as plt from matplotlib import animation import numpy as np fig, ax = plt.subplots()
我們的數據是一個0~2π內的正弦曲線:
x = np.arange(0, 2*np.pi, 0.01) line, = ax.plot(x, np.sin(x))
plt.show()

接着,構造自定義動畫函數animate,用來更新每一幀上各個x對應的y坐標值,參數表示第i幀:
def animate(i): line.set_ydata(np.sin(x + i/10.0)) return line,
然后,構造開始幀函數init:
def init(): line.set_ydata(np.sin(x)) return line,
2、參數設置
接下來,我們調用FuncAnimation函數生成動畫。參數說明:
fig進行動畫繪制的figurefunc自定義動畫函數,即傳入剛定義的函數animateframes動畫長度,一次循環包含的幀數init_func自定義開始幀,即傳入剛定義的函數initinterval更新頻率,以ms計blit選擇更新所有點,還是僅更新產生變化的點。應選擇True,但mac用戶請選擇False,否則無法顯示動畫
ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False)
plt.show()
當然,你也可以將動畫以mp4格式保存下來,但首先要保證你已經安裝了ffmpeg 或者mencoder, 更多信息參考matplotlib animation api:
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
