简单的Matplotlib动画不起作用

时间:2015-11-07 20:41:18

标签: python animation matplotlib

我正在尝试运行下面的代码,但它无法正常运行。我已经关注了matplotlib的文档,并想知道下面这个简单的代码有什么问题。我正在尝试使用anaconda发行版将其设置为jupyter笔记本。我的python版本是2.7.10。

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()

1 个答案:

答案 0 :(得分: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()
相关问题