[英]Combining outputs with differing axis onto one plot
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import pandas as pd
# Total population, N.
N = 100000
# Initial number of infected and recovered individuals, I0 and R0.
I0, R0 = 10, 0
# Everyone else, S0, is susceptible to infection initially.
S0 = N - I0 - R0
J0 = I0
# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).
#reproductive no. R zero is beta/gamma
beta, gamma = 1.47617188, 1/7
# A grid of time points (in days)
t = np.linspace(0, 77, 77+1)
t1 = [1,2,3,4,5,6,7,8,9,10,11]
# The SIR model differential equations.
def deriv(y, t, N, beta, gamma):
S, I, R, J = y
dS = ((-beta * S * I) / N)
dI = ((beta * S * I) / N) - (gamma * I)
dR = (gamma * I)
dJ = ((beta * S * I) / N)
return dS, dI, dR, dJ
# Initial conditions are S0, I0, R0
# Integrate the SIR equations over the time grid, t.
solve = odeint(deriv, (S0, I0, R0, J0), t, args=(N, beta, gamma))
S, I, R, J = solve.T
d = {'Week': [1, 2,3,4,5,6,7,8,9,10,11], 'incidence': [206.1705794,2813.420201,11827.9453,30497.58655,10757.66954,7071.878779,3046.752723,1314.222882,765.9763902,201.3800578,109.8982006]}
df = pd.DataFrame(data=d)
J_diff = J[1:] - J[:-1]
J_diff = np.diff(J)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t1, df, 'blue', alpha=1, lw=2, label='Daily incidence')
ax.set_xlabel('Time in days')
ax.set_ylabel('Number')
ax.grid(b=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
plt.show()
上面的代碼將 output 生成到 ODE 系統,然后我創建了一些值的數據框,我希望 plot 以及 ODE Z78E6221F6393D1356681DB398F14CED. 我了解時間點不同,ODE 系統使用天數,直到 77 天。 數據框以周為單位,直到 11 周,所以仍然是 77 天。 這就是為什么我將數據幀df
列在列表t1
到 plot 的原因。 然而,我上面的代碼輸出了一個 plot 和第三行,一條沿着 x 軸底部的水平線。 我的代碼有什么問題? 我需要對時間點做些什么來保持我的軸上的兩個輸出,ODE output J
和df
? 如果我想在第 20 天切斷軸?
對於這種特殊情況,我認為您不需要使用 pandas 。 如果你想 plot 字典中包含的數據,你可以簡單地做:
import numpy as np
import matplotlib.pyplot as plt
d = {'Week': np.arange(1, 12) * 7,
'incidence': [206.1705794, 2813.420201, 11827.9453, 30497.58655, 10757.66954, 7071.878779, 3046.752723, 1314.222882, 765.9763902, 201.3800578, 109.8982006]}
plt.plot(d['Week'], d['incidence'])
你得到水平線的原因是因為你從d
生成的 dataframe df
有兩列,當你 plot 它時,它會創建兩個系列,每列一個。 這里可以直接使用 dataframe plot
方法看到:
df = pd.DataFrame(d)
df.plot()
這不是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.