How to interactively change the parameters of an matplotlib.Animation?

Viewed 22

Good morning,

I have set up a code that:

  1. Asks the user to provide the value of a certain parameter through a slider
  2. On the basis of the given parameter, it solves an equation in the time domain
  3. It plots the results through an animation

I would like to change my code in such a way that the slider is always on (which is easy) and (difficult bit) when the user changes the value on the slider, points 2 and 3 are automatically updated on the updated value of the slider.

The big problem is that the equations are solved at the beginning with the first slider value, so if I change the slider value later on, this does not impact the equation solution. Could you please point me in the right direction?

Thanks

Here is the code:

import scipy
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import matplotlib.animation as animation 
import numpy as np

from matplotlib.widgets import Slider

#Fixed Parameters
yFp=0 #Fixed Point y
y0=0  #Initial Mass Position y
x0=4
m=1

#Slider to define the parameters
fig2 = plt.figure()

#Setting up the slider
axfreq = plt.axes([0.5, 0.9, 0.2, 0.05]) #Defining the slider position
Sliders=Slider(axfreq, 'Stiffness', 0, 5, valinit=0, valstep=1)
plt.show() #Showing the slider
k= Sliders.val

# create a time array
dt = 0.05
ti=0
N=1000
tf=ti+dt*N
t = np.arange(ti, tf, dt)

#Defining the differential equation of motion for a spring
def fun(t, x):
    x1, x2=x
    xdot1=x2
    xdot2=-1/m*(k*x1)
    return [xdot1, xdot2]



sol=scipy.integrate.solve_ivp(fun,[0, tf],[x0-(1), 0], t_eval=t)
t=sol.t
x1=sol.y[0]+(1)
x1dot=sol.y[1]

   

#Defining the main plot with point masses and springs
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(111, autoscale_on=False,xlim=(min(min(x1) , 0), max(x1)),  ylim=(-2, 2))
ax.grid()

point1,  = ax.plot([], [], 'o', color='blue', label='Mass')



def animate(i):
    point1.set_data(x1[i], y0) #point 1 coordinates
    return point1, 

ani = animation.FuncAnimation(fig, animate, np.arange(1, N),
                              interval=25, blit=True)
                              

plt.show()
 
0 Answers
Related