问题
I have a system of differential equations. The solutions depend on a parameter beta. I want to create a slider so I can change this parameter and display the changes of the solution curves directly in my plot. I almost got it I think, but I miss one piece.
My code
N = 1
#Initial conditions
I0 = 0.01
S0= N - I0
#System of diff. equations
def system(x, t, beta, gamma ):
I, S = x
dIdt = (beta/gamma*S-1)*I*gamma
dSdt = -(beta/gamma*S-1)*I*gamma
return dIdt, dSdt
#Parameters initial value
beta = 0.03
gamma = 0.017
#Initial cond. vector
y0 = I0, S0
#time grid
t = np.linspace(0, 1300, 1300)
# Solution
sol = odeint(system, y0, t, args=(beta, gamma))
################ Animations part ##################
fig, ax = plt.subplots()
plt.subplots_adjust(bottom = 0.25)
#solution curves for I and S
infected, = plt.plot(t, sol[:,0])
recovered, = plt.plot(t, sol[:,1])
axbeta = plt.axes([0.125, 0.1, 0.5, 0.05])
sliderbeta = Slider(axbeta, 'beta', 0, 1, valinit=beta)
def update_beta(val):
beta_value = sliderbeta.val
??????????????????????????????????????
fig.canvas.draw_idle()
sliderbeta.on_changed(update_beta)
plt.show()
I don't know how to acces my initial beta value and how to replace it by beta_value. I guess there is some line missing where I put the question marks.
回答1:
You take any ODE integration out of the global scope and migrate it to the update function. Following Automatically Rescale ylim and xlim in Matplotlib, one needs to add commands to compute the new limits and apply them.
# line objects for the solution curves for I and S
infected, = ax.plot([0], [0])
recovered, = ax.plot([0], [0])
def update_beta(beta):
# if triggered as call-back it passes the current slider value
# Solution
sol = odeint(system, y0, t, args=(beta, gamma))
# update the data for I and S
infected.set_data(t, sol[:,0])
recovered.set_data(t, sol[:,1])
# recompute the ax.dataLim
ax.relim()
# update ax.viewLim using the new dataLim
ax.autoscale_view()
fig.canvas.draw_idle()
And finally, to get an initial plot on startup, call this update function from the global scope once
update_beta(beta)
来源:https://stackoverflow.com/questions/61110496/updating-parameter-value-with-slider-python