Matplotlib 繪制疫情柱狀圖 動(dòng)畫
點(diǎn)擊上方藍(lán)色字體,選擇星標(biāo)公眾號(hào)

這是「Python與算法社區(qū)」第 417 篇原創(chuàng)
本文使用 matplotlib,繪制 COVID-19 過(guò)去半年四個(gè)國(guó)家的每天死亡人數(shù),獲取數(shù)據(jù)的API接口為:
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv
數(shù)據(jù)處理的邏輯如下,參考前幾天推送的處理邏輯:
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的部分?jǐn)?shù)據(jù):

整理后df1的部分?jǐn)?shù)據(jù):

可以看到截止昨天,美國(guó)COVID-19死亡人數(shù)已有:219286
繪制水平柱狀圖動(dòng)畫展示的邏輯如下:
fig?=?plt.figure(figsize=(9,16))
def?buildbarh(i=int):
????iv?=?min(i,?len(df1.index)-1)
????objects?=?df1.max().index
????y_pos?=?np.arange(len(objects))
????performance?=?df1.iloc[[iv]].values.tolist()[0]
????plt.barh(y_pos,?performance,?align='center',?color=['red',?'green',?'blue',?'orange'])
????plt.subplots_adjust(left=0.2)
????plt.yticks(y_pos,?objects)
????plt.xlabel('Deaths')
????plt.ylabel('Countries')
展示錄制的gif圖:

第26幀時(shí),各個(gè)變量的取值,放上這個(gè)圖方便大家迅速掌握這些代碼:

繪制動(dòng)畫只有這一行,調(diào)用FuncAnimation,它的第二個(gè)參數(shù)為上面定義的函數(shù)getmepie:
animator?=?ani.FuncAnimation(fig,?getmepie,?interval?=?200)
plt.show()
繪制豎直柱狀圖:
def?buildbar(i=int):
????iv?=?min(i,?len(df1.index)-1)
????objects?=?df1.max().index
????y_pos?=?np.arange(len(objects))
????performance?=?df1.iloc[[iv]].values.tolist()[0]
????plt.bar(y_pos,?performance,?align='center',?color=['red',?'green',?'blue',?'orange'])
????plt.subplots_adjust(left=0.2)
????plt.xticks(y_pos,?objects)
????plt.ylabel('Deaths')
????plt.xlabel('Countries')
????plt.title('Deaths?per?Country?\n'?+?str(df1.index[iv].strftime('%y-%m-%d')))
繪制后的gif圖:

關(guān)于本文有任何疑問(wèn)歡迎留言或加入討論群,在群里統(tǒng)一發(fā)放COVID-19數(shù)據(jù)文件:
評(píng)論
圖片
表情
