Matplotlib 绘制疫情动图:美国死亡超21万!

Python与算法社区

共 1444字,需浏览 3分钟

 ·

2020-10-20 18:41


本文使用 matplotlib,绘制 COVID-19 过去半年四个国家的每天死亡人数,获取数据的API接口为:


https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv


数据处理的逻辑如下,参考前几天推送的处理逻辑:

df = pd.read_csv('a.csv', delimiter=',', header='infer')
df_interest = df.loc[df['Country/Region'].isin(['United Kingdom''US''Italy''Germany'])& df['Province/State'].isna()]
df_interest.rename(index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
df1 = df_interest.transpose()
df1 = df1.drop(['Province/State''Country/Region''Lat''Long'])
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)

为了更方便大家理解,展示df_interest的部分数据:

整理后df1的部分数据:

可以看到截止昨天,美国COVID-19死亡人数已有:219286

绘制折线图动画展示的逻辑如下:

color = ['red''green''blue''orange']
fig = plt.figure()
plt.xticks(rotation=45, ha="right", rotation_mode="anchor")
plt.subplots_adjust(bottom = 0.2, top = 0.9)
plt.ylabel('No of Deaths')
plt.xlabel('Dates')

# 此函数是绘制动画的回调函数
# 有且仅有一个参数 i,表示帧数,表示df1的第几行
def showLine(i):
    plt.legend(df1.columns)
    p = plt.plot(df1[:i].index, df1[:i].values)
    for i in range(0,4):
        p[i].set_color(color[i])

绘制动画只有这一行,调用FuncAnimation,它的第二个参数为上面定义的函数showLine:

animator = ani.FuncAnimation(fig, showLine, interval = 10)
plt.show()

绘制后的折线图动画为:

关于本文有任何疑问欢迎留言或加入讨论群,在群里统一发放COVID-19数据文件:

长按加群讨论+数据文件发放

浏览 19
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报