首页 > 解决方案 > 使用 python(matplotlib、seaborn 或 plotly)将全球 COVID-19 演变绘制为线条

问题描述

作为练习,我正在尝试绘制由 Johns Hopkins CSSE 提供的出色的 COVID-19 数据。我很困惑,因为时间序列是按列组织的(每一天都放在另一边……见下图)。我希望避免将列转换为行,反之亦然。我的意图是将 COVID-19 的演变绘制为所有国家的线,日复一日(是的,它会变得一团糟)。

我在想我可以使用 for 循环遍历列来填充列表并将其用作我的 y 轴,但我们是否有更“直接”的方式来获取此图?最近我更多地使用 Plotly,但我也可以使用 matplotlib 或 seaborn。

在此处输入图像描述

标签: pythonpandasdataframematplotlibplotly

解决方案


我不认为这个特定的数据集非常适合 plotly.express 首选的长数据格式。特别是因为Province / State. 既然你的意图是

将 COVID-19 的演变绘制为所有国家的线,日复一日

...没有必要Province / State,LatLon。所以我只会对每个国家的数据求和,并使用go.Scatter每个国家的跟踪。不,它不会变得太混乱,因为您可以轻松地选择轨迹或关注字符的不同部分,因为我们在这里应用了 plotly 的强大功能。无论如何,我希望设置能满足您的喜好。如果您还有其他需要,请随时告诉我。

阴谋:

在此处输入图像描述

绘图,放大:

在此处输入图像描述

编辑 - 第 2 版:从第一次出现开始按天开发

使情节不那么混乱的一种方法是从每个区域第一次出现的第一天开始测量发展,如下所示:

在此处输入图像描述

为了生成第一个图,只需复制链接中的数据并将其存储covid.csv在名为c:\data.

第一个情节的完整代码:

import os
import pandas as pd
import plotly.graph_objects as go

dfi = pd.read_csv(r'C:\data\covid.csv',sep = ",", header = 0)

# drop province, latitude and longitude
df = dfi.drop(['Province/State', 'Lat', 'Long'], axis = 1)

# group by countries
df_gr = df.groupby('Country/Region').sum()#.reset_index()

time = df_gr.columns.tolist()
df_gr.columns = pd.to_datetime(time)
df_gr.reset_index(inplace = True)

# transpose df to get dates as a row index
df = df_gr.T

# set first row as header
new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

# order df columns descending by country with most cases
df_current = df.iloc[-1].to_frame().reset_index()
df_sort = df_current.sort_values(df_current.columns[-1], ascending = False)# plotly setup
order =  df_sort['Country/Region'].tolist()
df = df[order]

fig = go.Figure()

# add trace for each country
for col in df.columns:
    #print(col)
    fig.add_trace(go.Scatter(x=df.index, y=df[col].values, name=col))
fig.show()

最后一个情节的代码:

这建立在代码片段 1 中的 df 之上:

# replace leading zeros with nans
df2= df.replace({'0':np.nan, 0:np.nan})

# shift leading nans, leaving
# nans in the last rows for some
# regions
df2=df2.apply(lambda x: x.shift(-x.isna().sum()))
df2.reset_index(inplace=True)
df2=df2.drop('index', axis = 1)

fig2 = go.Figure()

# add trace for each country
for col in df2.columns:
    fig2.add_trace(go.Scatter(x=df2.index, y=df2[col].values
                              , name=col
                             ))
fig2.update_layout(showlegend=True)
fig2.update_layout(xaxis=dict(title='Days from first occurence'))
fig2.show()

推荐阅读