如何阻止 matplotlib 动画进入无限循环?

时间:2021-02-09 04:02:28

标签: matplotlib-animation

我正在 matplotlib 中学习动画。这是我简化的示例演示程序。它有效,但它永远不会终止。它在 plt.show() 中进入无限循环。 scope.update 的参数“n”始终为 0。根据手册页,我认为它应该在一帧后终止。为什么不呢?

import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation


class Scope:
    def __init__(self, ax, maxt=2, dt=0.02):
        self.ax = ax
        self.dt = dt
        self.maxt = maxt
        self.tdata = [0]
        self.ydata = [0]
        self.line = Line2D(self.tdata, self.ydata)
        self.ax.add_line(self.line)
        self.ax.set_ylim(-.1, 1.1)
        self.ax.set_xlim(0, self.maxt)

    def update(self, n):
        y = np.random.rand(1)
        lastt = self.tdata[-1]
        if lastt > self.tdata[0] + self.maxt:  # reset the arrays
            self.tdata = [self.tdata[-1]]
            self.ydata = [self.ydata[-1]]
            self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
            self.ax.figure.canvas.draw()

        t = self.tdata[-1] + self.dt
        self.tdata.append(t)
        self.ydata.append(y)
        self.line.set_data(self.tdata, self.ydata)
        return self.line,

def demo():

    fig, ax = plt.subplots()
    scope = Scope(ax)

    ani = animation.FuncAnimation(fig, scope.update, frames=1, interval=200,
                                  blit=True)
    plt.show()


demo()

0 个答案:

没有答案
相关问题