使用 Python 可视化 COVID-19 预测

我将演示如何创建病毒在全球范围内传播的两种可视化效果,提供开放数据并使用开源库。
145 位读者喜欢这个。
Open source voice control

Pixabay。由 Opensource.com 修改。CC BY-SA 4.0。

使用 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 对象,如下所示

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))  # Get first 3 entries in the dataframe
print(df1.tail(3))  # Get last 3 entries in the dataframe

数据集的顶行包含列名

  1. 日期
  2. 国家
  3. 确诊
  4. 治愈
  5. 死亡

head 查询的输出包括一个唯一标识符(未作为列列出)以及每个列的条目

0 2020-01-22 Afghanistan 0 0 0
1 2020-01-22 Albania 0 0 0
1 2020-01-22 Algeria 0 0 0

tail 查询的输出类似,但包含数据集的尾部

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

从输出中,您可以看到 DataFrame (df1) 具有以下列

  1. 日期
  2. 国家
  3. 确诊
  4. 治愈
  5. 死亡

此外,您可以看到 Date 列的条目从 1 月 22 日到 3 月 31 日。此数据库每天更新,因此您将获得当前值。

2. 选择印度的数据

在此步骤中,我们将仅选择 DataFrame 中包含印度的行。这在下面的脚本中显示

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

3. 绘制数据

这里我们创建一个条形图。我们将日期放在 X 轴上,将确诊病例数和死亡人数放在 Y 轴上。关于脚本的这一部分,有几点值得注意,如下所示

  • 代码行:plt.rcParams["figure.figsize"]=20,20 仅适用于 Jupyter。因此,如果您使用其他 IDE,请将其删除。

  • 请注意代码行:ax1 = plt.gca()。为了确保确诊病例和死亡人数的两个图都绘制在同一张图上,我们需要将第二个图的 ax 对象赋予它。因此我们使用 gca() 来做到这一点。(顺便说一句,'gca' 代表 'get current axis')。

完整脚本如下所示

#  Author:- Anurag Gupta # email:- 999.anuraggupta@gmail.com
%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()

整个脚本可在 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 对象

此步骤已在上一节中部分解释。

我们创建此类的对象的代码是

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

要给出的三个重要参数是

  • fig,必须给定一个 fig 对象,这是我们之前创建的。
  • func,必须是回调函数。
  • frames,必须包含要对其执行动画的变量。在我们的例子中,它将是我们之前创建的日期列表。

6. 将动画保存到 mp4 文件

您可以将创建的动画保存到 mp4 文件中。但是为此您需要 ffmpeg。您可以使用 pip 通过 pip install ffmpeg-python 下载它,或者使用 conda(在 Jupyter 上)install -c conda-forge ffmpeg

最后,您可以使用 plt.show() 运行动画。请注意,在许多平台上,ffmpeg 可能无法正常工作,可能需要进一步“调整”。

%matplotlib notebook
#  Author:- Anurag Gupta # email:- 999.anuraggupta@gmail.com
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()

完整脚本可在 GitHub 上获取

接下来阅读什么
User profile image.
Anurag Gupta 是一名受过教育的工程师,但职业是警察。他是一位 Python 爱好者,最近与人合着了一本关于 Python 的书,名为《Python Programming: Problem Solving, Packages and Libraries》,由 McGraw Hill 出版。您可以通过 999.anuraggupta 在 Gmail 上联系到他,并且他很乐意收到读者关于 Python 相关主题的来信。

4 条评论

我是一个 Python 新手。我一直无法获得 pycountry 和 plotly 这两个模块。我尝试过 Anaconda,但只能找到 pandas。请问您能告诉我如何获得这两个模块吗?谢谢

在使用 mp4 代码时,我收到以下异常

MovieWriter ffmpeg 不可用;改用 Pillow。
回溯(最近一次调用最后)
文件 "C:\Users\RJalo\OneDrive\Python_Scripts\covid19\test4.py",第 47 行,在
my_anim.save(filename = path_mp4, writer = 'ffmpeg',
文件 "C:\Users\RJalo\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\animation.py",第 1093 行,在 save
writer = writer_cls(fps, **writer_kwargs)
TypeError: __init__() 收到了意外的关键字参数 'extra_args'

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 获得许可。
© . All rights reserved.