1

I have som problems with buttons/animations in matplotlib. I'm trying to make an animation that starts when the button "start" is clicked on and stop when "stop" is clicked on. The problem is that the animation does not start when I click the button, only when I have moved my cursor off the button. The same goes for the stop button, it stops when my cursor is off the button. Also, the buttons does not get the "hovercolor" until the cursor has been moved of the button. I want the buttons to take affect immediately when I press them.

Here is my code:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from matplotlib.widgets import Button
from itertools import count

x_values = []
y_values = []

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

index = count()

def update_animation(i):
    ax.clear()
    t = next(index)
    x_values.append(t)
    y_values.append(np.sin(t))
    ax.plot(x_values, y_values)


def start_animation(event):
    global anim
    anim = animation.FuncAnimation(fig, update_animation, interval=100)
    anim.event_source.start()


def stop(event):
    global anim
    anim.event_source.stop()


startax = plt.axes([0.3, 0.1, 0.1, 0.05])
startbutton = Button(startax, label='Start', hovercolor='0.5')

stopax = plt.axes([0.5, 0.1, 0.1, 0.05])
stopbutton = Button(stopax, label='Stop', hovercolor='0.5')

startbutton.on_clicked(start_animation)
stopbutton.on_clicked(stop)
plt.show()

I have tried to add this to the "start_animation" function:

def start_animation(event):
    global anim
    anim = animation.FuncAnimation(fig, update_animation, interval=100)
    anim.event_source.start()
    if event.inaxes is not None:
        event.inaxes.figure.canvas.draw_idle()

From this thread: Make Matplotlib Button callback take effect immediately rather than after moving mouse off the button However, it did not change anything.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.