有幾種方法可以對matplotlib圖進行動畫處理.在下文中,我們將使用散點圖查看兩個最小示例.
(a)使用交互式模式plt.ion()
要進行動畫制作,我們需要一個事件循環.獲取事件循環的一種方法是使用plt.ion()(“交互式打開”).然后需要首先繪制圖形,然后可以循環更新繪圖.在循環內部,我們需要繪制畫布并為窗口引入一點暫停來處理其他事件(如鼠標交互等).沒有這個暫停,窗口就會凍結.最后我們調用plt.waitforbuttonpress()讓窗口保持打開狀態,即使動畫完成后也是如此.
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
plt.draw()
for i in range(1000):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
fig.canvas.draw_idle()
plt.pause(0.1)
plt.waitforbuttonpress()
(b)使用FuncAnimation
上面的大部分都可以使用matplotlib.animation.FuncAnimation自動完成.FuncAnimation將處理循環和重繪,并將在給定的時間間隔后不斷調用函數(在本例中為animate()).只有在調用plt.show()時動畫才會啟動,從而在繪圖窗口的事件循環中自動運行.
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
def animate(i):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=2, interval=100, repeat=True)
plt.show()