【问题标题】:How to stop FuncAnimation by func in matplotlib?如何通过 matplotlib 中的 func 停止 FuncAnimation?
【发布时间】:2018-02-01 13:42:08
【问题描述】:

我这样写一个matplotlib动画程序:

def animate(frame):
    observation = env.render()
    action = RL.choose_action(str(observation)) # TODO
    action = [random.randint(0, 4) for i in range(ROBOT_NUM)] # TO BE DELETE TODO
    env.step(action)
    observation_ = env.render()
    reward = env.reward
    RL.learn(str(observation), action, reward, str(observation_))  # TODO
    for i in range(TARGET_NUM):
        patchs_target[i].center = (env.targets[i].x, env.targets[i].y)
    for i in range(ROBOT_NUM):
        patchs[i].center = (env.robots[i].x, env.robots[i].y)
        patchs_inner[i].center = (env.robots[i].x, env.robots[i].y)
    return patchs + patchs_inner + patchs_target

.....

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

现在我想通过判断animate 函数中的条件来停止animation.FuncAnimation。比如if reward < 10然后停止animation.FuncAnimation,但我不知道如何处理。
或者是否有任何方法可以按条件停止animation.FuncAnimation?不是按动画时间。

【问题讨论】:

标签: python animation matplotlib


【解决方案1】:

两个选项:

(1) 使用生成器

为了动态控制动画,您可以使用生成器,只要满足某些条件,它就会在 while 循环中生成新值。这可能如下所示:

reward = 0

def gen():
    global reward
    i = 0
    while reward <= 10:
        i += 1
        yield i

def animate(i):
    global reward
    reward = update(reward)
    some_object[i] = func(reward)
    return some_object

anim = animation.FuncAnimation(fig, animate, frames=gen, repeat = False)

(2) 使用带有event_source.stop() 的类。

您也可以使用anim.event_source.stop() 停止动画。为了访问动画函数内部的动画,可以使用一个类并将动画设为类变量。

class Anim():
    def __init__(self, fig, **kw):
        self.reward=0
        self.ani = animation.FuncAnimation(fig, self.animate, 
                                           frames=100, repeat = False) 

    def animate(self,i):
        reward = update(reward)
        some_object[i] = func(reward)
        if self.reward > 10:
            self.ani.event_source.stop()
        return some_object

请注意,这两个代码都未经测试,因为问题没有提供测试用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多