2017-02-04 110 views
0

有沒有辦法在matplotlib中動畫製作圖形而不使用內置的動畫功能?我發現它們使用起來非常尷尬,並且覺得只需繪製一個點,擦除圖形,然後繪製下一個點就簡單多了。使用matplotlib進行動畫製作而不使用動畫功能

我設想一些諸如:

def f(): 
    # do stuff here 
    return x, y, t 

其中每個t將是不同的幀。

我的意思是,我試過像使用plt.clf()plt.close()等東西,但似乎沒有任何工作。

回答

2

肯定可以在沒有FuncAnimation的情況下生成動畫。然而,「設定的功能」的目的並不十分清楚。在動畫中,時間是自變量,即對於每個時間步,您都會生成一些新的數據以進行繪圖或類似操作。因此該函數將以t作爲輸入並返回一些數據。

import matplotlib.pyplot as plt 
import numpy as np 

def f(t): 
    x=np.random.rand(1) 
    y=np.random.rand(1) 
    return x,y 

fig, ax = plt.subplots() 
ax.set_xlim(0,1) 
ax.set_ylim(0,1) 
for t in range(100): 
    x,y = f(t) 
    # optionally clear axes and reset limits 
    #plt.gca().cla() 
    #ax.set_xlim(0,1) 
    #ax.set_ylim(0,1) 
    ax.plot(x, y, marker="s") 
    ax.set_title(str(t)) 
    fig.canvas.draw() 
    plt.pause(0.1) 

plt.show() 

而且,目前尚不清楚爲什麼你會希望避免FuncAnimation。同樣的動畫如上可以用FuncAnimation產生如下:

import matplotlib.pyplot as plt 
import matplotlib.animation 
import numpy as np 

def f(t): 
    x=np.random.rand(1) 
    y=np.random.rand(1) 
    return x,y 

fig, ax = plt.subplots() 
ax.set_xlim(0,1) 
ax.set_ylim(0,1) 

def update(t): 
    x,y = f(t) 
    # optionally clear axes and reset limits 
    #plt.gca().cla() 
    #ax.set_xlim(0,1) 
    #ax.set_ylim(0,1) 
    ax.plot(x, y, marker="s") 
    ax.set_title(str(t)) 

ani = matplotlib.animation.FuncAnimation(fig, update, frames=100) 
plt.show() 

沒有太多的變化,你有相同數量的行,沒有什麼尷尬的看這裏。
當動畫變得更加複雜時,當您想要重複動畫,想要使用blitting,或者想要將其導出到文件時,您還可以從FuncAnimation獲得所有好處。