如何基于双重排名的分组排序DataFrame绘制堆叠条形图
绘制带双重排名的堆叠条形图解决方案
没问题!针对你已经完成分组排序的双重结构DataFrame,我来给你一步步讲解如何实现目标堆叠条形图~
首先先确认下你的数据状态:你已经通过以下代码完成了数据的分组聚合、排序,并且将CPTY设为索引,得到了每个CPTY下按Gross Loan Amount降序排列的币种数据:
brkrcy=data[data['upload_date']==Date].groupby(['CPTY','currency'], as_index=False).agg({"Gross Loan Amount": "sum"}) brkrcy=brkrcy.sort_values(by=['CPTY', 'Gross Loan Amount'], ascending=[True, False]) brkrcy = brkrcy.set_index('CPTY')
接下来分两种常用实现方式,你可以根据需求选择:
方法一:利用Pandas内置绘图(快速简洁)
Pandas的plot方法可以直接处理宽格式数据生成堆叠条形图,所以第一步需要把你的长格式DataFrame转成宽格式:
# 将长格式转换为宽格式:currency作为列,CPTY作为行索引,值为对应金额 brkrcy_wide = brkrcy.pivot(columns='currency', values='Gross Loan Amount')
然后直接调用堆叠条形图绘制函数:
import matplotlib.pyplot as plt # 绘制堆叠条形图,设置尺寸 ax = brkrcy_wide.plot(kind='bar', stacked=True, figsize=(12, 6)) # 自定义图表样式 ax.set_title('Gross Loan Amount by CPTY & Currency (Double Ranked)', fontsize=14) ax.set_xlabel('CPTY', fontsize=12) ax.set_ylabel('Gross Loan Amount', fontsize=12) # 调整图例位置,避免遮挡图表 ax.legend(title='Currency', bbox_to_anchor=(1.05, 1), loc='upper left') # 自动调整布局,防止x轴标签被截断 plt.tight_layout() plt.show()
方法二:Matplotlib手动绘制(更灵活可控)
如果你需要更精细的样式控制(比如自定义每个堆叠部分的颜色、添加数值标签),可以用Matplotlib手动实现:
import matplotlib.pyplot as plt import numpy as np # 获取已排序的CPTY列表(保持你原有的排序顺序) cptys = brkrcy.index.unique() # 获取所有币种(可根据需求调整顺序) currencies = brkrcy['currency'].unique() # 设置x轴位置和条形宽度 x = np.arange(len(cptys)) bar_width = 0.8 # 初始化堆叠的底部基准线 bottom = np.zeros(len(cptys)) fig, ax = plt.subplots(figsize=(12, 7)) # 循环绘制每个币种的堆叠部分 for curr in currencies: # 提取当前币种对应每个CPTY的金额,缺失值补0 curr_amounts = brkrcy[brkrcy['currency'] == curr]['Gross Loan Amount'].reindex(cptys).fillna(0) # 绘制堆叠条形 ax.bar(x, curr_amounts, bar_width, bottom=bottom, label=curr) # 更新底部基准线,为下一个币种的堆叠做准备 bottom += curr_amounts.values # 可选:添加数值标签(只显示非零值) for idx, val in enumerate(curr_amounts.values): if val > 0: ax.text(x[idx], bottom[idx] - val/2, f'{val:.2e}', ha='center', va='center', fontsize=8) # 设置x轴标签,旋转45度避免重叠 ax.set_xticks(x) ax.set_xticklabels(cptys, rotation=45, ha='right') # 自定义标题和坐标轴标签 ax.set_title('Gross Loan Amount by CPTY & Currency (Double Ranked)', fontsize=14) ax.set_xlabel('CPTY', fontsize=12) ax.set_ylabel('Gross Loan Amount', fontsize=12) # 添加图例 ax.legend(title='Currency', bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()
注意点
- 两种方法都会保留你原有的
CPTY排序顺序,完美契合你的双重排名需求 - 如果希望每个
CPTY内的堆叠顺序是该CPTY下金额从大到小,可以在方法二中调整currencies的遍历顺序(针对每个CPTY单独排序),但视觉上统一币种顺序会更整洁,你可以根据需求权衡
内容的提问来源于stack exchange,提问作者SBad
相关产品推荐
相关产品推荐

