Python學習-使用matplotlib畫動態多圖,pythonmatplotlib
近期經常使用matplotlib進行數學函數圖的繪製,但是如何使用matplotlib繪製動態圖,以及繪製動態多圖,直到今天才學會。
1.參考文字
首先感謝幾篇文字的作者,幫我學會了如何繪製,大家也可以參考他們的文字。
2.程式源碼
先貼出程式源碼,在一步步做解釋。
<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>
3.解釋
現在就來解釋下,這個程式我究竟幹了啥
3.1建立子圖、空白線
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))就是建立子圖,關於子圖的概念和做法,大家可以參閱下文字【4】“用Python做科學計算”關於子圖的介紹。
3.2建立動畫發生時調用的函數
Init()是我們的動畫在在建立動畫基礎架構(base frame)時調用的函數。這裡我們們用一個非常簡單的對line什麼都不做的函數。這個函數一定要返回line對象,這個很重要,因為這樣就能告訴動畫之後要更新的內容,也就是動作的內容是line。--來自(http://mytrix.me/2013/08/matplotlib-animation-tutorial/)
上面的這段話,解釋了Init()這個函數是幹嘛的,因為我的程式比較特殊,希望能夠在一張圖中顯示兩個子圖,3.1。所以我必須在兩個座標軸ax1和ax2中建立兩個空白的線line,line2且在Init()中返回這兩個Line。
圖3.1
def init(): line.set_data([], []) line2.set_data([], []) return line,line2
3.3動畫函數接下來你需要一個動畫函數,在這個動畫函數中修改你的圖,同樣的我需要一張圖中顯示兩個東西,所以在動畫函數中,我更新了兩個圖,且返回了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
3.4顯示動畫最後你需要用如下的兩個語句來顯示動畫,這裡有個注意的地方,需要調整interval參數(這個參數指明了時間間隔)的大小,不然會出現3.2一樣的情況(當你使用了,blit=True這個選項)。同時(http://mytrix.me/2013/08/matplotlib-animation-tutorial/)給我們說明了幾個參數的作用,我在不在複述:
這個對象需要持續存在,所有我們要將它賦給一個變數,我們選擇了一個100幀的動畫(譯者註:你上邊的代碼還是200幀,怎麼到這兒就變成100幀了……,另外,這裡也不一定一定要是個數字,可以是個generator 或iterable,詳見API說明)並且幀與幀之間間隔20ms,blit是一個非常重要的關鍵字,它告訴動畫只重繪修改的部分,結合上面儲存的時間, blit=true會使動畫顯示得會非常非常快。
圖3.2
anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=50, interval=10) plt.show()
3.5結束
上面的工作解釋完了,來看看成果。程式寫的不好,我也是才初學,希望看到部落格的人,能多多給我指教,不勝感激。