# COVID-19 Data Visualization ## 說明 從美國John Hopkins 大學的公開新冠肺炎每日資訊來取得新冠肺炎資料,並載入Pandas DataFrame後座資料處理並以Matplotlib將資料視覺化輸出。 > 資料來源:https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_daily_reports ### 規格 #### 實現步驟 1. 從遠端載入資料到DataFrame。 2. 去除不需要的欄位資料。 3. 修改欄位名稱。 4. 合併相同國家的資料。 5. 取出前20名國家資料。 6. 建立視覺化圖表。 #### 會用到的模組 | 模組名稱 | 說明 | 安裝 | | ---------- | ---------------------------------- | --------------------------- | | pandas | Pandas資料處理和分析模組。 | `$ pip3 install pandas` | | matplotlib | matplotlib模組,用來將資料視覺化。 | `$ pip3 install matplotlib` | ## 完整程式碼 ``` import pandas as pd import matplotlib.pyplot as plt # 下載新冠廢園資料並載入DataFrame path = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-13-2021.csv' df = pd.read_csv(path) print(df.head()) # 過濾掉不需要的欄位 df.drop(['FIPS', 'Admin2','Last_Update','Province_State', 'Combined_Key'], axis=1, inplace=True) # 修改欄位名稱 df.rename(columns={'Country_Region': "Country"}, inplace=True) print(df.head()) # 合併相同國家的資料 world = df.groupby("Country")['Confirmed','Active','Recovered','Deaths'].sum().reset_index() # 取出前20名確診人數國家 top_20 = world.sort_values(by=['Confirmed'], ascending=False).head(20) print(top_20.head(20)) # 建立確診人數長條圖 plt.figure(figsize=(15,10)) plots = plt.barh(top_20['Country'], top_20['Confirmed'], height=0.5, left=None, align='center', color=['lightsteelblue', 'cornflowerblue', 'royalblue', 'midnightblue', 'navy', 'darkblue', 'mediumblue']) # 幫長條圖每個bar加上確診數字 for rect in plots: width = rect.get_width() plt.text(width, rect.get_y() + rect.get_height() / 2.0, '%d' % int(width), ha='left', va='center') # 建立復原人數長條圖 plt.barh(top_20['Country'], top_20['Recovered'], height=0.5, left=None, align='center', color=['bisque', 'darkorange', 'burlywood', 'antiquewhite', 'tan', 'navajowhite', 'wheat']) # 設定X軸的標籤 plt.xlabel('Confirmed') # 設定圖表的大標題 plt.title('CODID-19 Top 20 confirmed country') # 反轉Y軸的顯示順序為由大到小 plt.gca().invert_yaxis() # 顯示圖表 plt.show() ``` 執行結果: ![](https://hackmd.io/_uploads/HJpRdgc53.png) ### Matplotlib支援的顏色 ![](https://hackmd.io/_uploads/ryxlFg5c3.png) ![](https://hackmd.io/_uploads/BkceYgq93.png) ![](https://hackmd.io/_uploads/BJ0xYxcq2.png)