简单的Matplotlib动画无法正常工作 [英] Simple Matplotlib animate not working

查看:127
本文介绍了简单的Matplotlib动画无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在下面运行此代码,但无法正常工作.我遵循了matplotlib的文档,并想知道下面的简单代码有什么问题.我正在尝试使用anaconda发行版将此动画设置为jupyter笔记本.我的python版本是2.7.10.

I am trying to run this code below but it is not working properly. I've followed the documentation from matplotlib and wonder what is wrong with this simple code below. I am tryting to animate this into jupyter notebook with anaconda distro. My python version is 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()

推荐答案

您需要创建实际图.仅更新NumPy数组是不够的.这是一个示例,它可能会实现您的预​​期.由于必须在多个位置访问相同的对象,因此类似乎更适合,因为它允许通过 self :

You need to create an actual plot. Just updating a NumPy array is not enough. Here is an example that likely does what you intend. Since it is necessary to access the same objects at multiple places, a class seems better suited as it allows to access instance attributes via 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()

这篇关于简单的Matplotlib动画无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆