python - 使用 python(matplotlib、seaborn 或 plotly)将全球 COVID-19 演变绘制为线条
问题描述
作为练习,我正在尝试绘制由 Johns Hopkins CSSE 提供的出色的 COVID-19 数据。我很困惑,因为时间序列是按列组织的(每一天都放在另一边……见下图)。我希望避免将列转换为行,反之亦然。我的意图是将 COVID-19 的演变绘制为所有国家的线,日复一日(是的,它会变得一团糟)。
我在想我可以使用 for 循环遍历列来填充列表并将其用作我的 y 轴,但我们是否有更“直接”的方式来获取此图?最近我更多地使用 Plotly,但我也可以使用 matplotlib 或 seaborn。
解决方案
我不认为这个特定的数据集非常适合 plotly.express 首选的长数据格式。特别是因为Province / State
. 既然你的意图是
将 COVID-19 的演变绘制为所有国家的线,日复一日
...没有必要Province / State
,Lat
或Lon
。所以我只会对每个国家的数据求和,并使用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()
推荐阅读
- php - 基于 tr 计数的 td/th 的 XPath
- jenkins - 由于语法问题,无法执行 Jenkins 管道
- django - 在 AWS 上免费部署 Django VC,哪个最好?只是 EC2.t2 或 Beanstalk
- node.js - 在 Express.js 中发出请求和响应处理程序会导致问题吗?
- eclipse - 什么是 Buildship,是否有适用于 NetBeans 的 Gradle 插件?
- amazon-web-services - 从区域 A 到其他各个区域的多区域 EC2 和 RDS 复制
- python - 终端和 subprocess.run() 显示命令的不同行为(osmfilter)
- sql - 需要查询以列出两列相对相同的行,但需要注意 Postgresql
- android - Pepper 机器人已连接但在连接的设备上显示离线
- php - 注意:未定义的索引:第 59 行 C:\xampp\htdocs\dbkaryawan\report.php 中的 tgl1