近期經(jīng)常使用matplotlib進行數(shù)學函數(shù)圖的繪制,但是如何使用matplotlib繪制動態(tài)圖,以及繪制動態(tài)多圖,直到今天才學會。
首先感謝幾篇文字的作者,幫我學會了如何繪制,大家也可以參考他們的文字。
先貼出程序源碼,在一步步做解釋。
<span style="font-family:SimSun;font-size:10px;">import numpy as np from matplotlib import pyplot as plt from matplotlib import animation # first set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax1 = fig.add_subplot(2,1,1,xlim=(0, 2), ylim=(-4, 4))ax2 = fig.add_subplot(2,1,2,xlim=(0, 2), ylim=(-4, 4))line, = ax1.plot([], [], lw=2) line2, = ax2.plot([], [], lw=2) def init(): line.set_data([], []) line2.set_data([], []) return line,line2# animation function. this is called sequentially def animate(i): x = np.linspace(0, 2, 100) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) x2 = np.linspace(0, 2, 100) y2 = np.cos(2 * np.pi * (x2 - 0.01 * i))* np.sin(2 * np.pi * (x - 0.01 * i)) line2.set_data(x2, y2) return line,line2anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=50, interval=10) plt.show() </span>
現(xiàn)在就來解釋下,這個程序我究竟干了啥
fig = plt.figure() ax1 = fig.add_subplot(2,1,1,xlim=(0, 2), ylim=(-4, 4))ax2 = fig.add_subplot(2,1,2,xlim=(0, 2), ylim=(-4, 4))line, = ax1.plot([], [], lw=2) line2, = ax2.plot([], [], lw=2)
在上面的程序可以看到,先建立了一個figure對象,之后fig.add_subplot(2,1,1,xlim=(0, 2), ylim=(-4, 4))就是建立子圖,關(guān)于子圖的概念和做法,大家可以參閱下文字【4】“ 用Python做科學計算” 關(guān)于子圖的介紹。
Init()是我們的動畫在在創(chuàng)建動畫基礎(chǔ)框架(base frame)時調(diào)用的函數(shù)。這里我們們用一個非常簡單的對line什么都不做的函數(shù)。這個函數(shù)一定要返回line對象,這個很重要,因為這樣就能告訴動畫之后要更新的內(nèi)容,也就是動作的內(nèi)容是line。--來自( http://mytrix.me/2013/08/matplotlib-animation-tutorial/ )
上面的這段話,解釋了Init()這個函數(shù)是干嘛的,因為我的程序比較特殊,希望能夠在一張圖中顯示兩個子圖,如圖3.1。所以我必須在兩個坐標軸ax1和ax2中創(chuàng)建兩個空白的線line,line2且在Init()中返回這兩個Line。
圖3.1
def init(): line.set_data([], []) line2.set_data([], []) return line,line2
接下來你需要一個動畫函數(shù),在這個動畫函數(shù)中修改你的圖,同樣的我需要一張圖中顯示兩個東西,所以在動畫函數(shù)中,我更新了兩個圖,且返回了line和line2
def animate(i): x = np.linspace(0, 2, 100) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) x2 = np.linspace(0, 2, 100) y2 = np.cos(2 * np.pi * (x2 - 0.01 * i))* np.sin(2 * np.pi * (x - 0.01 * i)) line2.set_data(x2, y2) return line,line2
最后你需要用如下的兩個語句來顯示動畫,這里有個注意的地方,需要調(diào)整interval參數(shù)(這個參數(shù)指明了時間間隔)的大小,不然會出現(xiàn)如圖3.2一樣的情況(當你使用了,blit=True這個選項)。
同時 ( http://mytrix.me/2013/08/matplotlib-animation-tutorial/ )給我們說明了幾個參數(shù)的作用,我在不在復(fù)述:
這個對象需要持續(xù)存在,所有我們要將它賦給一個變量,我們選擇了一個100幀的動畫(譯者注:你上邊的代碼還是200幀,怎么到這兒就變成100幀了……,另外,這里也不一定一定要是個數(shù)字,可以是個generator 或iterable,詳見API說明)并且?guī)c幀之間間隔20ms,blit是一個非常重要的關(guān)鍵字,它告訴動畫只重繪修改的部分,結(jié)合上面保存的時間, blit=true會使動畫顯示得會非常非???。
圖3.2
anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=50, interval=10) plt.show()
上面的工作解釋完了,來看看成果。程序?qū)懙牟缓茫乙彩遣懦鯇W,希望看到博客的人,能多多給我指教,不勝感激。