停止/开始/暂停在Python matplotlib动画 [英] stop / start / pause in python matplotlib animation

查看:5741
本文介绍了停止/开始/暂停在Python matplotlib动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的一些基本的动画matplotlib动画模块FuncAnimation。这个功能永远通过动画循环。有没有通过,我可以停下来,比方说,鼠标点击?

I'm using FuncAnimation in matplotlib's animation module for some basic animation. This function perpetually loops through the animation. Is there a way by which I can pause and restart the animation by, say, mouse clicks?

推荐答案

下面是 我修改了一个FuncAnimation例子暂停鼠标点击。
由于动画是由发生器功能驱动, SIMDATA ,当全局变量暂停为True,产生相同的数据使得动画出现暂停。

Here is a FuncAnimation example which I modified to pause on mouse clicks. Since the animation is driven by a generator function, simData, when the global variable pause is True, yielding the same data makes the animation appear paused.

价值暂停是通过建立一个事件回调切换:

The value of paused is toggled by setting up an event callback:

def onClick(event):
    global pause
    pause ^= True
fig.canvas.mpl_connect('button_press_event', onClick)


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

pause = False
def simData():
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0
    while t < t_max:
        if not pause:
            x = np.sin(np.pi*t)
            t = t + dt
        yield x, t

def onClick(event):
    global pause
    pause ^= True

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'bo', ms=10) # I'm still not clear on this stucture...
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)

time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
fig.canvas.mpl_connect('button_press_event', onClick)
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10,
    repeat=True)
plt.show()

这篇关于停止/开始/暂停在Python matplotlib动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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