如何用Pandas和Matplotlib绘制带交易数标注的银行交易柱状图?
解决方案
你之前生成两个子图是因为slised_two包含tr_type和average_income两列,用plot.bar(subplots=True)会把每列单独画成子图。要实现单图展示average_income的柱状图并标注tr_type,按以下步骤操作:
1. 绘制核心柱状图
只针对average_income列绘制柱状图,去掉subplots=True参数:
import matplotlib.pyplot as plt # 绘制average_income的柱状图 ax = slised_two['average_income'].plot.bar(rot=0, figsize=(10, 6))
2. 在柱子顶部标注tr_type数值
遍历每个柱子,获取对应位置的tr_type值,在柱子顶部添加文本标注:
# 遍历所有柱子添加标注 for p in ax.patches: # 获取柱子对应的行索引 row_idx = int(p.get_x()) # 取出对应的tr_type数值 tr_count = slised_two.iloc[row_idx]['tr_type'] # 在柱子顶部居中位置添加文本 ax.text(p.get_x() + p.get_width()/2, p.get_height() + p.get_height()*0.01, # 位置稍高于柱子避免重叠 f'{tr_count}', ha='center', va='bottom')
3. 优化图表细节
添加标题、轴标签,调整布局让图表更清晰:
ax.set_title('Top 5 Days by Average Income (with Transaction Count)', fontsize=12) ax.set_xlabel('Day', fontsize=10) ax.set_ylabel('Average Income', fontsize=10) plt.tight_layout() plt.show()
完整代码示例
import pandas as pd import matplotlib.pyplot as plt # 保留你的数据预处理代码 slised_two = sliced_df_new.sort_values('average_income', ascending=False).head(5) slised_two = slised_two.set_index('day') # 绘制柱状图并添加标注 ax = slised_two['average_income'].plot.bar(rot=0, figsize=(10, 6)) for p in ax.patches: row_idx = int(p.get_x()) tr_count = slised_two.iloc[row_idx]['tr_type'] ax.text(p.get_x() + p.get_width()/2, p.get_height() + p.get_height()*0.01, f'{tr_count}', ha='center', va='bottom') ax.set_title('Top 5 Days by Average Income', fontsize=12) ax.set_xlabel('Day') ax.set_ylabel('Average Income') plt.tight_layout() plt.show()
运行后就能得到你想要的单图效果:x轴显示day,y轴显示average_income,每个柱子顶部标注对应的交易数量tr_type。
内容的提问来源于stack exchange,提问作者Lisa
相关产品推荐
相关产品推荐

