2015-11-07 79 views
1

我想在下面运行这段代码,但它不能正常工作。我遵循matplotlib的文档,并想知道下面这个简单的代码有什么问题。我正在尝试使用anaconda发行版将它制作成jupyter笔记本。我的Python版本是2.7.10。简单的Matplotlib动画不起作用

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

fig = plt.figure() 

def init(): 
    m = np.zeros(4800) 
    m[0] = 1.6 
    return m 

def animate(i): 
    for a in range(1,4800): 
     m[a] = 1.6 
     m[a-1] = 0 
    return m  

anim = animation.FuncAnimation(fig, animate, init_func=init, 
           frames=200, interval=20, blit=True) 

plt.show() 
+2

你能解释一下什么是不工作?你得到了什么,你期望什么?你的代码的一个问题当然是你没有绘制任何东西。你看过matplotlib动画例子吗? –

+0

我在这里尝试的是获取值1.6并将其移动到每个交互的右侧。因此,例如在时间t = 1时,我想有[1.6,0,0,0,0],在时间t = 2 [0,1.6,0,0,0]等上。我已经看过这些例子,但是所有这些看起来都很复杂,因为我在这里寻找的是简单的东西。我清楚了吗? – Mensch

回答

3

您需要创建一个实际图。只更新一个NumPy数组是不够的。 这是一个可能做你想要的例子。由于需要在多个地方访问相同的对象,一类似乎更适合,因为它允许访问例如通过self属性:

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



class MyAni(object): 
    def __init__(self, size=4800, peak=1.6): 
     self.size = size 
     self.peak = peak 
     self.fig = plt.figure() 
     self.x = np.arange(self.size) 
     self.y = np.zeros(self.size) 
     self.y[0] = self.peak 
     self.line, = self.fig.add_subplot(111).plot(self.x, self.y) 

    def animate(self, i): 
     self.y[i - 1] = 0 
     self.y[i] = self.peak 
     self.line.set_data(self.x, self.y) 
     return self.line, 

    def start(self): 
     self.anim = animation.FuncAnimation(self.fig, self.animate, 
      frames=self.size, interval=20, blit=False) 

if __name__ == '__main__': 
    ani = MyAni() 
    ani.start() 

    plt.show() 
+0

为什么你最后要添加__name__ ='__main__'? – Mensch

+0

if __name__ =='__main __':'仅在模块(此源文件)用作程序时(即在控制台:python my_program.py)时才会执行。如果此模块由另一个模块('import my_program')导入,则此部分将被跳过。这不以任何方式特定于此动画。 –