matplotlib / pyplot:绘制多个图的平均曲线
Posted
技术标签:
【中文标题】matplotlib / pyplot:绘制多个图的平均曲线【英文标题】:matplotlib / pyplot: plot average curve for multiple graphs 【发布时间】:2022-01-22 08:40:18 【问题描述】:我是 matplotlib 的初学者。 我已经从数据框中创建了一些图表。 现在我想从多个图表中创建平均图表。
谁能帮我解决这个问题?
我的图表如下所示:
alb = df[df.location == 'Albania']
bel = df[df.location == 'Belarus']
bih = df[df.location == 'Bosnia and Herzegovina']
blg = df[df.location == 'Bulgaria']
cro = df[df.location == 'Croatia']
hun = df[df.location == 'Hungary']
kos = df[df.location == 'Kosovo']
mld = df[df.location == 'Moldova']
mng = df[df.location == 'Montenegro']
nmc = df[df.location == 'North Macedonia']
pol = df[df.location == 'Poland']
rom = df[df.location == 'Romania']
rus = df[df.location == 'Russia']
srb = df[df.location == 'Serbia']
tur = df[df.location == 'Turkey']
ukr = df[df.location == 'Ukraine']
plt.plot(alb.date, alb.new_deaths_per_million)
plt.plot(bel.date, bel.new_deaths_per_million)
plt.plot(bih.date, bih.new_deaths_per_million)
plt.plot(blg.date, blg.new_deaths_per_million)
plt.plot(cro.date, cro.new_deaths_per_million)
plt.plot(hun.date, hun.new_deaths_per_million)
plt.plot(kos.date, kos.new_deaths_per_million)
plt.plot(mld.date, mld.new_deaths_per_million)
plt.plot(mng.date, mng.new_deaths_per_million)
plt.plot(nmc.date, nmc.new_deaths_per_million)
plt.plot(pol.date, pol.new_deaths_per_million)
plt.plot(rom.date, rom.new_deaths_per_million)
plt.plot(rus.date, rus.new_deaths_per_million)
plt.plot(srb.date, srb.new_deaths_per_million)
plt.plot(tur.date, tur.new_deaths_per_million)
plt.plot(ukr.date, ukr.new_deaths_per_million)
plt.legend(['Albania', 'Belarus', 'Bosnia and Herzegovina', 'Bulgaria', 'Croatia', 'Hungary', 'Kosovo', 'Moldova', 'Montenegro', 'North Macedonia', 'Poland', 'Romania', 'Russia', 'Serbia', 'Turkey', 'Ukraine'])
plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 200
plt.show()
图表如下所示:
这是我使用的数据集:
url = 'https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv'
df = pd.read_csv(url,error_bad_lines=False)
pd.options.display.max_columns = None
display(df)
现在我想从所有这些图表中创建平均曲线。 有人可以帮我写代码吗?如何以最简单的方式做到这一点?
提前感谢您的帮助!
【问题讨论】:
【参考方案1】:最简单的方法是取所有国家/地区的案例的平均值并绘制此图。您可以通过创建一个新的DataFrame
来做到这一点:
frames = [alb, bel, bih, blg, cro, hun, kos, mld, mng, nmc, pol, rom, rus, srb, tur, ukr]
result = pd.concat(frames)[["date", "new_deaths_per_million"]] # Only select the relevant columns for now
result = result.groupby(["date"], as_index=False).mean() # Take the mean of all the values on the same date
print(result)
输出:
date new_deaths_per_million
2020-01-31 NaN
2020-02-01 NaN
2020-02-02 NaN
2020-02-03 NaN
2020-02-04 NaN
... ...
2021-12-15 7.698063
2021-12-16 6.557625
2021-12-17 7.023750
2021-12-18 4.249562
2021-12-19 3.559250
然后您也可以绘制此图 - 就像您对所有国家所做的那样。请注意,您似乎缺少一些数据,导致 NaN
(不是数字)值。您可能需要先清理一下数据。
【讨论】:
嗨@Bjorn,非常感谢您的帮助!工作完美! @AdmirRamic 很高兴听到。 :-)以上是关于matplotlib / pyplot:绘制多个图的平均曲线的主要内容,如果未能解决你的问题,请参考以下文章
Python机器学习入门——科学计算库(Matplotlib)