You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib中如何将堆叠条形图标签置于顶部并设置白色字体?

堆叠条形图标签移至顶部并设置白色字体的实现

修改后的完整代码

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # 补全seaborn导入,原代码遗漏

data = [['2005','A',10],['2006','A',15],['2007','A',10],
                       ['2005','B',15],['2006','B',70],['2007','B',10],
                       ['2005','C',75],['2006','C',15],['2007','C',80]
                      ]

df = pd.DataFrame(
    data=data, 
    columns=['year','type','count'])

fig, ax = plt.subplots(figsize=(15, 7),facecolor = '#fdf1e6')
ax.set_facecolor('#fdf1e6')

ax = sns.histplot(df, x='year', 
                  hue='type', 
                  weights='count',
                  multiple='stack', 
                  shrink=0.9,
                  linewidth=3.5,
                  )

ax.get_legend().remove()

# 调整标签设置:移至顶部、白色字体
for c in ax.containers:
    ax.bar_label(c, 
                 fmt=lambda x: f'{x}' if x > 0 else '',  # 显示原始数值,若需占比需先计算
                 label_type='edge',  # 标签移至条形顶部边缘
                 color='white',      # 设置字体颜色为白色
                 padding=3)          # 调整标签与条形的间距

plt.show()  # 新增显示图表的代码

关键改动说明

  • 补全依赖库:原代码使用了seaborn的histplot但未导入,必须添加import seaborn as sns才能避免报错
  • 调整标签属性:
    • 将label_type='center'改为label_type='edge',直接把标签从堆叠块中心移到顶部边缘
    • 新增color='white'参数,设置标签字体为白色
    • 添加padding=3,让标签和条形顶部保持一定距离,避免重叠影响可读性
  • 修正数值格式:原代码的百分比格式化会把原始count值(如10)转为1000%,不符合常规展示逻辑,这里改为显示原始数值。如果需要展示每个堆叠块在对应年份的占比,可以参考以下代码:
# 先计算每年的总count,再转换为占比
df['total_year'] = df.groupby('year')['count'].transform('sum')
df['proportion'] = df['count'] / df['total_year']

# 绘图时使用占比作为权重
ax = sns.histplot(df, x='year', 
                  hue='type', 
                  weights='proportion',
                  multiple='stack', 
                  shrink=0.9,
                  linewidth=3.5,
                  )

# 标签格式化显示百分比
for c in ax.containers:
    ax.bar_label(c, 
                 fmt=lambda x: f'{x:.0%}' if x > 0 else '',
                 label_type='edge',
                 color='white',
                 padding=3)

内容的提问来源于stack exchange,提问作者Mato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:43:16