使用 Python 來可視化 COVID-19 預測 | Linux 中國

使用 Python 來可視化 COVID-19 預測 | Linux 中國

我將演示如何利用提供的全球病毒傳播的開放數據,使用開源庫來創建兩個可視效果。

  • 來源:https://linux.cn/article-12172-1.html
  • 作者:Anuraggupta
  • 譯者:Xingyu.Wang


使用 Python 和一些圖形庫,你可以預測 COVID-19 確診病例總數,也可以顯示一個國家(本文以印度為例)在給定日期的死亡總數。人們有時需要幫助解釋和處理數據的意義,所以本文還演示瞭如何為五個國家創建一個動畫橫條形圖,以顯示按日期顯示病例的變化。

印度的確診病例和死亡人數預測

這要分三步來完成。

1、下載數據

科學數據並不總是開放的,但幸運的是,許多現代科學和醫療機構都樂於相互之間及與公眾共享信息。關於 COVID-19 病例的數據可以在網上查到,並且經常更新。

要解析這些數據,首先必須先下載。 https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv 。

直接將數據加載到 Pandas DataFrame 中。Pandas 提供了一個函數 read_csv(),它可以獲取一個 URL 並返回一個 DataFrame 對象,如下所示。

<code>import pycountry
import plotly.express as px
import pandas as pd
URL_DATASET = r'https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv'
df1 = pd.read_csv(URL_DATASET)
print(df1.head(3))  # 獲取數據幀中的前 3 項
print(df1.tail(3))  # 獲取數據幀中的後 3 項/<code>

數據集的頂行包含列名。

  1. Date
  2. Country
  3. Confirmed
  4. Recovered
  5. Deaths

head 查詢的輸出包括一個唯一的標識符(不作為列列出)和每個列的條目。

<code>0 2020-01-22 Afghanistan 0 0 0
1 2020-01-22 Albania 0 0 0
1 2020-01-22 Algeria 0 0 0/<code>

tail 查詢的輸出類似,但包含數據集的尾端。

<code>12597 2020-03-31 West Bank and Gaza 119 18 1
12598 2020-03-31 Zambia 35 0 0
12599 2020-03-31 Zimbabwe 8 0 1/<code>

從輸出中,可以看到 DataFrame(df1)有以下幾個列:

  1. 日期
  2. 國家
  3. 確診
  4. 康復
  5. 死亡

此外,你可以看到 Date 欄中的條目從 1 月 22 日開始到 3 月 31 日。這個數據庫每天都會更新,所以你會有當前的值。

2、選擇印度的數據

在這一步中,我們將只選擇 DataFrame 中包含印度的那些行。這在下面的腳本中可以看到。

<code>#### ----- Step 2 (Select data for India)----
df_india = df1[df1['Country'] == 'India']
print(df_india.head(3))/<code>

3、數據繪圖

在這裡,我們創建一個條形圖。我們將把日期放在 X 軸上,把確診的病例數和死亡人數放在 Y 軸上。這一部分的腳本有以下幾個值得注意的地方。

  • plt.rcParams["figure.figsize"]=20,20 這一行代碼只適用於 Jupyter。所以如果你使用其他 IDE,請刪除它。
  • 注意這行代碼:ax1 = plt.gca()。為了確保兩個圖,即確診病例和死亡病例的圖都被繪製在同一個圖上,我們需要給第二個圖的 ax 對象。所以我們使用 gca() 來完成這個任務。(順便說一下,gca 代表 “ 獲取當前座標軸(get current axis)”)

完整的腳本如下所示。

<code>#  Author:- Anurag Gupta # email:- [email protected]
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd

#### ----- Step 1 (Download data)----
URL_DATASET = r'https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv'
df1 = pd.read_csv(URL_DATASET)
# print(df1.head(3))  # Uncomment to see the dataframe

#### ----- Step 2 (Select data for India)----
df_india = df1[df1['Country'] == 'India']
print(df_india.head(3))

#### ----- Step 3 (Plot data)----
# Increase size of plot
plt.rcParams["figure.figsize"]=20,20  # Remove if not on Jupyter
# Plot column 'Confirmed'
df_india.plot(kind = 'bar', x = 'Date', y = 'Confirmed', color = 'blue')

ax1 = plt.gca()
df_india.plot(kind = 'bar', x = 'Date', y = 'Deaths', color = 'red', ax = ax1)
plt.show()/<code>

整個腳本 可在 GitHub 上找到 。

為五個國家創建一個動畫水平條形圖

關於 Jupyter 的注意事項:要在 Jupyter 中以動態動畫的形式運行,而不是靜態 png 的形式,你需要在單元格的開頭添加一個神奇的命令,即: %matplotlib notebook。這將使圖形保持動態,而不是顯示為靜態的 png 文件,因此也可以顯示動畫。如果你在其他 IDE 上,請刪除這一行。

1、下載數據

這一步和前面的腳本完全一樣,所以不需要重複。

2、創建一個所有日期的列表

如果你檢查你下載的數據,你會發現它有一列 Date。現在,這一列對每個國家都有一個日期值。因此,同一個日期會出現多次。我們需要創建一個只具有唯一值的日期列表。這會用在我們條形圖的 X 軸上。我們有一行代碼,如 list_dates = df[‘Date’].unique()。unique() 方法將只提取每個日期的唯一值。

3、挑選五個國家並創建一個 ax 對象。

做一個五個國家的名單。(你可以選擇你喜歡的國家,也可以增加或減少國家的數量。)我也做了一個五個顏色的列表,每個國家的條形圖的顏色對應一種。(如果你喜歡的話,也可以改一下。)這裡有一行重要的代碼是:fig, ax = plt.subplots(figsize=(15, 8))。這是創建一個 ax 對象所需要的。

4、編寫回調函數

如果你想在 Matplotlib 中做動畫,你需要創建一個名為 matplotlib.animation.FuncAnimation 的類的對象。這個類的簽名可以在網上查到。這個類的構造函數,除了其他參數外,還需要一個叫 func 的參數,你必須給這個參數一個回調函數。所以在這一步中,我們會寫個回調函數,這個回調函數會被反覆調用,以渲染動畫。

5、創建 FuncAnimation 對象

這一步在上一步中已經部分說明了。

我們創建這個類的對象的代碼是:

<code>my_anim = animation.FuncAnimation(fig = fig, func = plot_bar,
                    frames = list_dates, blit = True,
                    interval=20)/<code> 

要給出的三個重要參數是:

  • fig,必須給出一個 fig 對象,也就是我們之前創建的 fig 對象。
  • func,必須是回調函數。
  • frames,必須包含要做動畫的變量。在我們這裡,它是我們之前創建的日期列表。

6、將動畫保存為 mp4 文件

你可以將創建的動畫保存為 mp4 文件。但是,你需要 ffmpeg。你可以用 pip 下載:pip install ffmpeg-python,或者用 conda(在 Jupyter 上):install -c conda-forge ffmpeg。

最後,你可以使用 plt.show() 運行動畫。請注意,在許多平臺上,ffmpeg 可能無法正常工作,可能需要進一步“調整”。

<code>%matplotlib notebook
#  Author:- Anurag Gupta # email:- [email protected]
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from time import sleep

#### ---- Step 1:- Download data
URL_DATASET = r'https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv'
df = pd.read_csv(URL_DATASET, usecols = ['Date', 'Country', 'Confirmed'])
# print(df.head(3)) # uncomment this to see output

#### ---- Step 2:- Create list of all dates
list_dates = df['Date'].unique()
# print(list_dates) # Uncomment to see the dates

#### --- Step 3:- Pick 5 countries. Also create ax object
fig, ax = plt.subplots(figsize=(15, 8))
# We will animate for these 5 countries only
list_countries = ['India', 'China', 'US', 'Italy', 'Spain']
# colors for the 5 horizontal bars
list_colors = ['black', 'red', 'green', 'blue', 'yellow']

### --- Step 4:- Write the call back function
# plot_bar() is the call back function used in FuncAnimation class object
def plot_bar(some_date):
    df2 = df[df['Date'].eq(some_date)]
    ax.clear()
    # Only take Confirmed column in descending order
    df3 = df2.sort_values(by = 'Confirmed', ascending = False)
    # Select the top 5 Confirmed countries
    df4 = df3[df3['Country'].isin(list_countries)]
    # print(df4)  # Uncomment to see that dat is only for 5 countries
    sleep(0.2)  # To slow down the animation
    # ax.barh() makes a horizontal bar plot.
    return ax.barh(df4['Country'], df4['Confirmed'], color= list_colors)

###----Step 5:- Create FuncAnimation object---------
my_anim = animation.FuncAnimation(fig = fig, func = plot_bar,
                    frames= list_dates, blit=True,
                    interval=20)

### --- Step 6:- Save the animation to an mp4
# Place where to save the mp4. Give your file path instead
path_mp4 = r'C:\Python-articles\population_covid2.mp4'  
# my_anim.save(path_mp4, fps=30, extra_args=['-vcodec', 'libx264'])
my_anim.save(filename = path_mp4, writer = 'ffmpeg',
             fps=30,
             extra_args= ['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
plt.show()/<code>

完整的腳本 可以在 GitHub 上找到 。

via: https://opensource.com/article/20/4/python-data-covid-19

作者: AnuragGupta 選題: lujun9972 譯者: wxy 校對: wxy

本文由 LCTT 原創編譯, Linux中國 榮譽推出

點擊“瞭解更多”可訪問文內鏈接


分享到:


相關文章: