0

I would like to pause and resume animation when click on figure by mouse, but it does not work, please help me to fix it, thank you,

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

x = np.arange(100)
y = np.arange(10, 110)

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

fig = plt.figure()
ax = fig.add_subplot()

line, = ax.plot([], [])

ax.set_ylim(0, 120)
ax.set_xlim(0, 100)


def runData(i):

    line.set_data(x[:i], y[:i])

    return line

fig.canvas.mpl_connect('button_press_event', onClick)    

ani = animation.FuncAnimation(fig, runData, frames=len(x), blit=False, interval=10, repeat=True)

plt.show()
haidang
  • 1
  • 1

1 Answers1

0

You need to verify pause in the runData(). Here is it:

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

x = np.arange(100)
y = np.arange(10, 110)

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

fig = plt.figure()
ax = fig.add_subplot()
line, = ax.plot([], [])
ax.set_ylim(0, 120)
ax.set_xlim(0, 100)

def runData(i):
    if not pause:
        line.set_data(x[:i], y[:i])
        return line

fig.canvas.mpl_connect('button_press_event', onClick)    
ani = animation.FuncAnimation(fig, runData, frames=len(x), blit=False, interval=10, repeat=True)
fig.show()
Pedro
  • 330
  • 2
  • 12