python matplotlib动画中的停止/启动/暂停 [英] stop / start / pause in python matplotlib animation
问题描述
我在 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
驱动,当全局变量 pause
为 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.
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)
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)
time_template = 'Time = %.1f s'
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)
fig.show()
这篇关于python matplotlib动画中的停止/启动/暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!