使用python(matplotlib、seaborn或plotly)将全球COVID19演变绘制为线条

2024-04-29 22:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

作为练习,我正在尝试绘制优秀的COVID-19 data provided by Johns Hopkins CSSE。 我很困惑,因为时间序列是按列组织的(每天都放在另一天的一边…见下图)。首先,我希望避免将列转换为行,反之亦然。我的意图是将新冠病毒-19的演变描绘成所有国家的界线,日复一日(是的,它会变得一团糟)

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

enter image description here


Tags: databy时间绘制序列国家意图provided
2条回答

我不认为这个特定的数据集非常适合plotly.express首选的长数据格式。特别是由于Province / State的许多缺失观测。既然你的目的是

plot the COVID-19 evolution as lines for all countries, day by day

…不需要Province / StateLatLon。因此,我只需对每个国家的数据求和,并使用每个国家的go.Scatter跟踪。不,它不会变得太混乱,因为你可以很容易地选择痕迹或集中在字符的不同部分,因为我们在这里应用了plotly的强大功能。无论如何,我希望设置将满足您的喜好。如果您还需要什么,请随时告诉我

绘图:

enter image description here

绘图,缩放:

enter image description here

编辑-第2版:按首次出现后的天数进行开发

一种使绘图不那么凌乱的方法是测量每个区域从第一天开始的发展情况,如下所示:

enter image description here

为了生成第一个绘图,只需复制链接中的数据,并将其作为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()

plotly处理整洁的数据,这需要您将日期转换为一列。我将使用pandas melt将日期列转换为单个列,然后进行绘图。根据我使用plotly的经验,最好了解plotly是如何喜欢数据结构化的(整洁的数据帧),并将我的数据集转换成这种形式,而不是尝试以另一种方式创建数据集

我认为,如果您的数据像图中所示那样简单,那么以下内容将使其成为正确的形式:

pd.melt(df, id_vars=['Country/Region'])

有关plotly如何喜欢此处数据的详细信息https://plotly.com/python/px-arguments/

更多关于熊猫融化的信息请点击这里https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html

相关问题 更多 >