首页 > 解决方案 > 如何按类别绘制数据框列

问题描述

我有来自这里的数据集

我添加了另一个名称为摘要的列。

我正在尝试绘制 x=date 和 y=summary每个国家/地区都有单独的行。


    
new_df = df["Country"].isin(["Germany","Canada","United Kingdom","US","France","China","India"])
new_df = df[new_df]
new_df = pd.DataFrame(new_df)


col_list = ['Confirmed','Recovered','Deaths']
new_df["Summary"] = new_df[col_list].sum(axis=1)

new_df['Date'] = pd.Series(pd.to_datetime(df['Date']))
print(new_df.tail())

            Date         Country  Confirmed  Recovered  Deaths  Summary
91811 2021-05-30  United Kingdom    4499937      15486  128043  4643466
91812 2021-05-31  United Kingdom    4503231      15507  128045  4646783
91813 2021-06-01  United Kingdom    4506333      15508  128045  4649886
91814 2021-06-02  United Kingdom    4510597      15514  128057  4654168
91815 2021-06-03  United Kingdom    4515778      15517  128075  4659370

我想绘制这样的图(每个国家的增长线在不同的线上)

在此处输入图像描述

标签: pythonpython-3.xpandasdataframeplot

解决方案


导入 Seabornimport seaborn as sns并用 Seaborn 绘制它:

sns.lineplot(data=new_df, x="Date", y="Summary", hue="Country")

在此处输入图像描述

要仅获取 2021 年的日期,您需要像这样修改数据框:

new_df = new_df[pd.DatetimeIndex(new_df["Date"]).year >= 2021]

推荐阅读