我正在尝试编写大流行模拟的代码。我有一个 csv 文件,其中包含 3 组数据: S(易受影响)– 我(传染性) – R(已恢复)- . 我想在同一个二维图中绘制所有三个列表(s,i,r)。这样我们就可以在同一个图中看到三个图。其中 x 轴是天数,y 轴是百分比(例如从 0 到 1)。我在制作这些图时遇到问题,这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
s = []
i = []
r = []
with open("pan.csv","r") as f:
lis = [line.split(",") for line in f]
for n in range(1,121):
s.append(int(lis[n][0]))
i.append(float(lis[n][1]))
r.append(float(lis[n][2]))
n_list= [s, i, r]
fig = plt.figure()
ax = fig.add_subplot()
w = [s, i, r]
w_np = np.array(w)
# ax.plot(s, range(1)) here I have the problem
plt.show()
有人可以帮我画图吗?
尝试在同一个图中绘制三个 2d 图(x 来自三个列表,y 介于 0-1 之间的百分比)。
如果你已经在使用 NumPy,你可以这样做
import numpy as np
import matplotlib.pyplot as plt
# optional, see below
from matplotlib.ticker import MaxNLocator
s, i, r = np.genfromtxt("pan.csv", delimiter=',', unpack=True)
days = np.arange(1, len(s)+1, dtype=int)
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(days, s)
ax.plot(days, i)
ax.plot(days, r)
# This is optional: it will enforce axis ticks to be integers
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.show()
将数据标准化为百分比,并对每组使用绘图函数。
import numpy as np
import matplotlib.pyplot as plt
s = []
i = []
r = []
with open("pan.csv", "r") as f:
lis = [line.split(",") for line in f]
for n in range(1, 121):
s.append(int(lis[n][0]))
i.append(float(lis[n][1]))
r.append(float(lis[n][2]))
s = np.array(s)
i = np.array(i)
r = np.array(r)
s_percentage = s / (s + i + r)
i_percentage = i / (s + i + r)
r_percentage = r / (s + i + r)
fig, ax = plt.subplots()
ax.plot(s_percentage, label='Susceptible')
ax.plot(i_percentage, label='Infectious')
ax.plot(r_percentage, label='Recovered')
ax.set_xlabel('Days')
ax.set_ylabel('Percentage')
ax.set_title('Pandemic Simulation')
ax.legend()
plt.show()