2017-02-04 49 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获得所有好处。