[英]How to add an interactive plot in Jupyter Notebook?
我為基本的 SIR model 制作了 plot。 我對我的 plot 感到滿意,但是,我希望能夠有一個交互式 slider 來調整我的參數 beta 和 gamma。 我希望它們的范圍都在 0 到 1 之間,並且用戶能夠將它們增加 0.01。
有人可以幫我在我的代碼中實現這個嗎? 提前感謝您的時間。
這是我的代碼:
# # Solving SIR Model in Python (INTERACTIVE)
# \
# Importing packages:
# In[10]:
# Display in LaTeX style.
from sympy.interactive import printing
printing.init_printing(use_latex = True)
# For integration.
import scipy.integrate
# For arrays (Python does not have native arrays).
import numpy as np
# For graphing.
import matplotlib.pyplot as plt
# Prevents the pop-up graphs in a separate window.
get_ipython().run_line_magic('matplotlib', 'inline')
# Allows for an interactive widget bar.
from ipywidgets import interactive
# \
# Defining differential equations:
# In[11]:
def SIR_model(y, t, beta, gamma):
S, I, R = y
dS_dt = -beta*S*I
dI_dt = beta*S*I - gamma*I
dR_dt = gamma*I
return([dS_dt, dI_dt, dR_dt,])
# \
# Defining initial conditions:
# In[12]:
S0 = 0.95
I0 = 0.05
R0 = 0.0
beta = 0.35
gamma = 0.1
# \
# Defining time vector:
# In[13]:
# Graph from 0 to 100, include 10000 points.
t = np.linspace(0, 100, 10000)
# \
# Defining solution:
# In[14]:
# Result
solution = scipy.integrate.odeint(SIR_model, [S0, I0, R0], t, args=(beta, gamma))
solution = np.array(solution)
# \
# Plotting the result:
# In[20]:
plt.figure(figsize=[8, 5])
plt.plot(t, solution[:, 0], label="S(t)")
plt.plot(t, solution[:, 1], label="I(t)")
plt.plot(t, solution[:, 2], label="R(t)")
plt.grid()
plt.legend()
plt.title("SIR Model")
plt.xlabel("Time")
plt.ylabel("Proportions of Populations")
# THIS DOES NOT WORK !!!
#interactive_plot = interactive(SIR_model, betta=(0.35,1,0.01), gamma=(0.1,1,0.01))
#interactive_plot
plt.show()
這是 output。
您需要創建一個 function 來處理輸入、集成和在一個 go ( sir_interactive_func
) 中繪制所有內容,見下文:
# For integration.
import scipy.integrate
# For arrays (Python does not have native arrays).
import numpy as np
# For graphing.
import matplotlib.pyplot as plt
# Prevents the pop-up graphs in a separate window.
get_ipython().run_line_magic('matplotlib', 'inline')
# Allows for an interactive widget bar.
from ipywidgets import interactive
S0 = 0.95
I0 = 0.05
R0 = 0.0
def SIR_model(y, t, beta, gamma):
S, I, R = y
dS_dt = -beta*S*I
dI_dt = beta*S*I - gamma*I
dR_dt = gamma*I
return([dS_dt, dI_dt, dR_dt,])
def sir_interactive_func(beta, gamma):
# Graph from 0 to 100, include 10000 points.
t = np.linspace(0, 100, 10000)
solution = scipy.integrate.odeint(SIR_model, [S0, I0, R0], t, args=(beta, gamma))
solution = np.array(solution)
plt.figure(figsize=[8, 5])
plt.plot(t, solution[:, 0], label="S(t)")
plt.plot(t, solution[:, 1], label="I(t)")
plt.plot(t, solution[:, 2], label="R(t)")
plt.grid()
plt.legend()
plt.title("SIR Model")
plt.xlabel("Time")
plt.ylabel("Proportions of Populations")
interactive_plot = interactive(sir_interactive_func, beta=(0.35,1,0.01), gamma=(0.1,1,0.01))
interactive_plot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.