Я использую FuncAnimation в модуле анимации matplotlib для некоторой базовой анимации. Эта функция постоянно проходит анимацию. Есть ли способ, с помощью которого я могу приостановить и перезапустить анимацию, скажем, щелчками мыши?stop/start/pause in python matplotlib animation
ответ
Здесь a FuncAnimation example, который я модифицировал, чтобы сделать паузу на щелчки мыши. Поскольку анимация управляется генераторной функцией, simData
, когда глобальная переменная pause
имеет значение True, при получении одинаковых данных анимация оказывается приостановленной.
Значение paused
переключается путем установки обратного вызова события:
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)
plt.show()
Это работает ...
anim = animation.FuncAnimation(fig, animfunc[,..other args])
#pause
anim.event_source.stop()
#unpause
anim.event_source.start()
сочетающая ответы от @fred и @unutbu здесь, мы можем добавить функцию onClick после создания анимации:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def run_animation():
anim_running = True
def onClick(event):
nonlocal anim_running
if anim_running:
anim.event_source.stop()
anim_running = False
else:
anim.event_source.start()
anim_running = True
def animFunc(...args...):
# Animation update function here
fig.canvas.mpl_connect('button_press_event', onClick)
anim = animation.FuncAnimation(fig, animFunc[,...other args])
run_animation()
Теперь мы можем просто остановить или запустить анимацию с помощью кликов.
Какую версию matplotlib вы используете? Это не работает для меня – bretcj7
@ bretcj7 Я использую версию 1.5.3. Извините, надо было бы это упомянуть! – woodenflute
Я не могу найти документацию по matplotlib для event_source.stop() или начать? Он существует? – bretcj7
- 1. matplotlib animation in wxpython panel
- 2. Matplotlib Animation
- 3. Django Matplotlib Animation embed in templates
- 4. Save Matplotlib Animation
- 5. Cmap in matplotlib Python
- 6. Choppy animation in Pygame
- 7. Android Animation «Rolling in»
- 8. jquery animation in wordpress
- 9. Android fade in animation
- 10. swf animation in wpf
- 11. ImageView Animation in Steps
- 12. UIButton Animation in Swift
- 13. Native Animation in iOS
- 14. Looped animation in ImageView
- 15. JLabel animation in JPanel
- 16. Kivy Fade-In Animation
- 17. Interpolation animation in Unity
- 18. clearRect issue in animation
- 19. UIView Animation in SubClass
- 20. DIV fade in animation
- 21. jQuery animation in select
- 22. plt.bar (matplotlib in python) не делает баров
- 23. Python matplotlib insert index in plot
- 24. Python - matplotlib subplots in tripcolor case
- 25. Matplotlib python change single color in colormap
- 26. clear ax2 in matplotlib
- 27. Matplotlib Subplot Animation с базовой картой
- 28. Page Curl Animation in android?
- 29. toggle & animation in sencha touch
- 30. Fade Out/In UiView Animation
Отлично, спасибо вам большое! Это сделало трюк для меня. –
Смазливая, удобная, развлекательная, и в некотором смысле ностальгическая; https://youtu.be/TxmZ5sabk7U?t=17 или https://youtu.be/C1HuX6nQnQY?t=211 – uhoh