Python畫圖 : matplotlib的animation的基本範例
matplotlib是python一個很流行的圖表繪製模組
強項是在繪製漂亮的圖表
弱點是在速度
以下是利用matplotlib的animation模組做的一個圖表動畫小範例
我的環境是: window10,Python3.6,
下面是我寫的程式碼
程式碼解釋我哪天有空再來補
存起來的mp4檔在這裡
需要注意的是
這個matplotlib模組是要自行安裝的(如果還沒安裝numpy的話安裝方法跟matplotlib一樣)
安裝方法很簡單,在cmd輸入
要儲存影片的話,需要安裝一個第三方軟體叫做ffmpeg,這裡是下載連結
解壓縮之後要設定系統的環境變數
這個教學影片教得很仔細也很簡單
這些安裝都算輕鬆,沒什麼大問題
好了,今天的筆記到此結束
希望有幫助未來遺忘這些的自己,以及需要的人
強項是在繪製漂亮的圖表
弱點是在速度
以下是利用matplotlib的animation模組做的一個圖表動畫小範例
我的環境是: window10,Python3.6,
下面是我寫的程式碼
程式碼解釋我哪天有空再來補
#matplotlib_animation_sample.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
A = range(-5,5)
xdata, ydata = [], []
xdata2, ydata2 = [], []
xdata3, ydata3 = [], []
ln1, ln2, ln3, ln4 = ax.plot([], [], 'r-',
[], [], 'b-',
[], [], 'y-',
[], [], 'c-',
animated=False) #animated is associated with blit
def init():
ax.set_xlim(0, 10)
ax.set_ylim(-6, 6)
return ln1,ln2,ln3,ln4
def update(i): #i is an int from 0 to frames-1, and keep looping
ax.set_xlim(i/250, 10+i/250)
global A
iter = int(i/50)
if i==0:
xdata.clear()
ydata.clear()
xdata2.clear()
ydata2.clear()
iter = 0
xdata.append(i/50)
ydata.append(A[iter])
xdata2.append(i/50)
ydata2.append(np.cos(i/100))
xdata3.append(i/50)
ydata3.append(np.cos(i/100-np.pi))
ln1.set_data(xdata, ydata)
ln2.set_data(xdata2, ydata2)
ln3.set_data(xdata3, ydata3)
x = np.linspace(0, 10, 1000)
y = np.sin(np.pi*(x + i/100))
ln4.set_data(x, y)
iter += 1
return ln1, ln2, ln3, ln4
def main():
ani = FuncAnimation(fig, update, frames = 500, interval = 20,
init_func=init, blit=False)
ani.save('animation.mp4', writer='ffmpeg', fps=30) /save as .mp4
plt.show() /show result
if __name__ == '__main__':
main()
存起來的mp4檔在這裡
需要注意的是
這個matplotlib模組是要自行安裝的(如果還沒安裝numpy的話安裝方法跟matplotlib一樣)
安裝方法很簡單,在cmd輸入
pip install matplotlib
要儲存影片的話,需要安裝一個第三方軟體叫做ffmpeg,這裡是下載連結
解壓縮之後要設定系統的環境變數
這個教學影片教得很仔細也很簡單
這些安裝都算輕鬆,沒什麼大問題
希望有幫助未來遺忘這些的自己,以及需要的人

五體投地。
回覆刪除