如何在python中使用matplotlib绘制正确的covid跟踪时间序列图?

2024-04-28 20:11:13 发布

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

我想追踪该公司每个机构中新的covid19病例编号,即每日时间序列。我想看看如何通过漂亮的EDA绘图实时跟踪新的covid19病例。我试图在一页中为每个公司绘制直方图,但无法绘制正确的直方图。有人能告诉我怎么做吗?有什么想法吗

可再现数据

以下是可再现的covid19跟踪时间序列数据in this gist。在此数据中,est是指establishment code,因此每个不同的公司可能有多个机构代码

我的尝试

以下是我对seaborns和matplotlib的尝试:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
from datetime import timedelta, datetime

bigdf = pd.read_csv("coviddf.csv")

markers = {"new_case_sum": "s", "est_company": "X"}
for t in bigdf.company.unique():
    grouped = bigdf[bigdf.company==t]
    res = grouped.groupby(['run_date','county-state', 'company'])['new'].sum().unstack().reset_index('run_date')
    f, axes = plt.subplots(nrows=len(bigdf.company), ncols= 1, figsize=(20, 7), squeeze=False)
    for j in range(len(bigdf.company)):
        p = sns.scatterplot('run_date', 'new', data=res, hue='company', markers=markers, style='cats', ax=axes[j, 0])
        p.set_title(f'Threshold: {t}\n{pt}')
        p.set_xlim(data['run_date'].min() - timedelta(days=60), data['run_date'].max() + timedelta(days=60))
        plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left", borderaxespad=0)

但我不能得到正确的情节。我认为我为绘图数据做了正确的数据聚合,但不知何故,我使用了错误的数据属性来渲染绘图。有人能告诉我哪里错了吗?有人能提出更好的方法来实现这一点吗?有什么想法吗

所需绘图

理想情况下,我希望呈现类似此结构的绘图(所附的所需绘图仅为其他站点的参考):

enter image description here

有人能建议如何使我的上述方法正确吗?有没有更好的建议来为新冠病毒追踪绘制更好的时间序列图?谢谢

更新

在我的尝试中,我试图通过每个公司的所有机构汇总新的案例数量,然后制作折线图或直方图。我们如何制作折线图,将每个公司内所有机构的所有确诊病例、死亡病例和新病例(也称为est列)沿日期绘制在一页图中?有什么办法可以做到这一点吗


Tags: 数据runinimport绘图date机构时间
1条回答
网友
1楼 · 发布于 2024-04-28 20:11:13
  • 下面的代码将使用^{}^{}
  • 每行将是company,每列将是每个estbarplot
    • x轴将为run_date。我添加了额外的数据,因此将有两个日期
    • y轴和hue将是newconfirmeddeadval
  • ^{}用于^{}newconfirmeddead堆叠到一列中
import pandas as pd
import seaborn as sns

# load and clean data
df = pd.read_csv("https://gist.githubusercontent.com/jerry-shad/318595505684ea4248a6cc0949788d33/raw/31bbeb08f329b4b96605b8f2a48f6c74c3e0b594/coviddf.csv")
df.drop(columns=['Unnamed: 0'], inplace=True)  # drop this extra column
df.run_date = pd.to_datetime(df.run_date)  # set run_date to a datetime format

# plot
for g, d in df.groupby(['company']):
    data = d.groupby(['run_date','county-state', 'company', 'est'], as_index=True).agg({'new': sum, 'confirmed': sum, 'death': sum}).stack().reset_index().rename(columns={'level_4': 'type', 0: 'val'})
#     display(data)  # if you're not using Jupyter, change display to print
#     print('\n')
    print(f'{g}')
    g = sns.FacetGrid(data, col='est', sharex=False, sharey=False, height=5, col_wrap=4)
    g.map(sns.barplot, 'run_date', 'val', 'type', order=data.run_date.dt.date.unique(), hue_order=data['type'].unique())
    g.add_legend()
    g.set_xticklabels(rotation=90)
    g.set(yscale='log')
    plt.tight_layout()
    plt.show()

groupby{}的示例

     run_date      county-state company  est       type    val
0  2020-08-30    ColfaxNebraska  Vergin  86M        new      2
1  2020-08-30    ColfaxNebraska  Vergin  86M  confirmed    718
2  2020-08-30    ColfaxNebraska  Vergin  86M      death      5
3  2020-08-30        FordKansas  Vergin  86K        new      0
4  2020-08-30        FordKansas  Vergin  86K  confirmed   2178
5  2020-08-30        FordKansas  Vergin  86K      death     10
6  2020-08-30  FresnoCalifornia  Vergin  354        new      0
7  2020-08-30  FresnoCalifornia  Vergin  354  confirmed  23932
8  2020-08-30  FresnoCalifornia  Vergin  354      death    239
9  2020-08-30    MorganColorado  Vergin  86R        new      1
10 2020-08-30    MorganColorado  Vergin  86R  confirmed    711
11 2020-08-30    MorganColorado  Vergin  86R      death     48
12 2020-08-30       ParmerTexas  Vergin  86E        new      1
13 2020-08-30       ParmerTexas  Vergin  86E  confirmed    381
14 2020-08-30       ParmerTexas  Vergin  86E      death      7

示例图

enter image description here

用地理数据绘图

import pandas as pd
import plotly.express as px

# load and clean data
df = pd.read_csv("https://gist.githubusercontent.com/jerry-shad/318595505684ea4248a6cc0949788d33/raw/31bbeb08f329b4b96605b8f2a48f6c74c3e0b594/coviddf.csv")
df.drop(columns=['Unnamed: 0'], inplace=True)  # drop this extra column
df.run_date = pd.to_datetime(df.run_date)  # set run_date to a datetime format

# convert to long form
dfl = df.set_index(['company', 'est', 'latitude', 'longitude'])[['confirmed', 'new', 'death']].stack().reset_index().rename(columns={'level_4': 'type', 0: 'vals'})

# plot
fig = px.scatter_geo(dfl,
                     lon='longitude',
                     lat='latitude',
                     color="type", # which column to use to set the color of markers
                     hover_name="company", # column added to hover information
                     size="vals", # size of markers
                     projection="albers usa")
fig.show()

enter image description here

相关问题 更多 >