如何在Seaborn绘图中使用sum函数聚合裁员数据?
问题:按行业+年份聚合裁员总数绘制分组条形图
我有一个带PeriodIndex的裁员数据集,样例如下:
Industry Laid_Off_Count Year 2022-10 Finance 0.0 2022-10 Healthcare 0.0 2022-09 Consumer 600.0 2022-09 Healthcare 113.0 2022-09 Finance 85.0 2020-03 Travel 0.0 2020-03 Transportation 8.0 2020-03 Consumer 6.0 2020-12 Retail 20.0 2020-11 All Others 75.0 1791 rows × 2 columns
行业唯一值:
array(['Finance', 'Healthcare', 'Consumer', 'All Others', 'Food', 'Transportation', 'Real Estate', 'Retail', 'Travel'], dtype=object)
我当前用以下代码绘图:
fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot() sns.histplot(data=df_copy3,y='Industry',hue=df_copy3.index.year,ax=ax,multiple='dodge',stat='count') plt.savefig('Tech layoffs by Industry.jpeg')
但我需要把X轴改成按行业和年份分组的裁员总数,用sum聚合,实现类似分组条形图的效果,该怎么做?
解决方案
seaborn.histplot的stat参数不支持sum,要实现需求的分组条形图,推荐两种方式:
方式1:先手动聚合数据,再绘图
先提取年份为单独列,再按行业+年份分组计算裁员总数,最后绘制条形图:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 从索引提取年份到新列 df_copy3['Year'] = df_copy3.index.year # 按行业、年份分组,求和裁员数 agg_df = df_copy3.groupby(['Industry', 'Year'])['Laid_Off_Count'].sum().reset_index() # 绘制分组条形图 fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot() sns.barplot(data=agg_df, y='Industry', x='Laid_Off_Count', hue='Year', ax=ax, dodge=True) plt.xlabel('裁员总数') plt.ylabel('行业') plt.title('各行业年度裁员总数') plt.savefig('Tech layoffs by Industry.jpeg')
方式2:直接用barplot指定聚合函数
seaborn.barplot支持通过estimator参数指定聚合逻辑,无需提前分组,直接传入原数据即可:
import seaborn as sns import matplotlib.pyplot as plt fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot() # 指定estimator=sum,直接按行业和年份聚合求和 sns.barplot(data=df_copy3, y='Industry', x='Laid_Off_Count', hue=df_copy3.index.year, ax=ax, dodge=True, estimator=sum) plt.xlabel('裁员总数') plt.ylabel('行业') plt.title('各行业年度裁员总数') plt.savefig('Tech layoffs by Industry.jpeg')
两种方式都能实现目标效果:Y轴为行业,X轴对应各行业每年的裁员总数,不同年份用颜色区分。
内容的提问来源于stack exchange,提问作者Victor
相关产品推荐
相关产品推荐

