點擊上方藍色字體,選擇星標公衆號css
這是「Python與算法社區」第 417 篇原創
git
本文使用 matplotlib,繪製 COVID-19 過去半年四個國家的天天死亡人數,獲取數據的API接口爲:
github
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csvweb
數據處理的邏輯以下,參考前幾天推送的處理邏輯:算法
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
的部分數據:app
能夠看到截止昨天,美國COVID-19死亡人數已有:219286dom
繪製水平柱狀圖動畫展現的邏輯以下:函數
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幀時,各個變量的取值,放上這個圖方便你們迅速掌握這些代碼:
繪製動畫只有這一行,調用FuncAnimation
,它的第二個參數爲上面定義的函數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圖:
關於本文有任何疑問歡迎留言或加入討論羣,在羣裏統一發放COVID-19數據文件:
本文分享自微信公衆號 - Python與算法社區(alg-channel)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。