Python堆叠柱状图中为数值添加千位分隔符的问题
堆叠柱状图千位数值逗号分隔格式化问题
我尝试绘制一幅堆叠柱状图,希望为千位数值添加逗号分隔(例如7000显示为7,000,20000显示为20,000)。我尝试在图表中添加代码fmt='{:,.0f}',但没有效果,也找不到该格式化方式的清晰说明。
我的完整代码如下:
ax = dfp_vort_monthly.plot.bar(stacked=True, figsize=(16, 10), ylabel='UNCONVERTED CASE COUNTS', xlabel='WEEK ENDING', title='VOORTMAN Weekly Percentage Bins and Case Counts') for c in ax.containers: label = c.get_label() labels = [v.get_height() if v.get_height() > 0 else '' for v in c] ax.bar_label(c, labels=labels, label_type='edge',fmt='{:,.0f}', fontweight='bold', color= 'blue') _ = ax.legend(title='Percentage Bins', bbox_to_anchor=(1.0, 1.0), loc='upper left') _ = ax.margins(y=0.3)
解决方法
问题根源是你手动生成了labels列表并传入bar_label,此时fmt参数会被忽略——matplotlib会直接使用你提供的标签文本,不再执行格式化。可以通过两种方式修复:
方式一:在生成标签时直接格式化数值
修改labels的生成逻辑,对高度值应用千位分隔格式化:
ax = dfp_vort_monthly.plot.bar(stacked=True, figsize=(16, 10), ylabel='UNCONVERTED CASE COUNTS', xlabel='WEEK ENDING', title='VOORTMAN Weekly Percentage Bins and Case Counts') for c in ax.containers: label = c.get_label() # 生成标签时直接格式化数值 labels = [f'{v.get_height():,.0f}' if v.get_height() > 0 else '' for v in c] ax.bar_label(c, labels=labels, label_type='edge', fontweight='bold', color='blue') _ = ax.legend(title='Percentage Bins', bbox_to_anchor=(1.0, 1.0), loc='upper left') _ = ax.margins(y=0.3)
方式二:移除手动生成的labels,依赖fmt自动格式化
去掉自定义的labels参数,使用fmt和empty_string处理空值:
ax = dfp_vort_monthly.plot.bar(stacked=True, figsize=(16, 10), ylabel='UNCONVERTED CASE COUNTS', xlabel='WEEK ENDING', title='VOORTMAN Weekly Percentage Bins and Case Counts') for c in ax.containers: label = c.get_label() # 不手动指定labels,让fmt生效,用empty_string处理高度为0的情况 ax.bar_label(c, label_type='edge', fmt='{:,.0f}', fontweight='bold', color='blue', empty_string='') _ = ax.legend(title='Percentage Bins', bbox_to_anchor=(1.0, 1.0), loc='upper left') _ = ax.margins(y=0.3)
内容的提问来源于stack exchange,提问作者vanetoj
相关产品推荐
相关产品推荐

