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

如何为堆叠柱状图(bar chart)的每个分段区块添加数值标签

堆叠柱状图所有分段区块添加标签的最简实现

用Matplotlib 3.4.0及以上版本内置的bar_label()方法即可实现,不需要手动计算每个标签的坐标,修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt

x = ['A', 'B', 'C', 'D']
y1 = np.array([2, 4, 5, 1])
y2 = np.array([1, 0, 2, 3])
y3 = np.array([4, 1, 1, 1])

# 每绘制一层柱状图,就调用一次bar_label添加对应标签
p1 = plt.bar(x, y1, color='#d67ed0')
plt.bar_label(p1) # 给第一层紫色块加标签

p2 = plt.bar(x, y2, color='#e6ad12', bottom=y1)
plt.bar_label(p2) # 给第二层黄色块加标签

p3 = plt.bar(x, y3, color='#13c5ed', bottom=y1+y2)
plt.bar_label(p3) # 给第三层蓝色块加标签

plt.show()
  • plt.bar()的返回值是当前层所有柱状块的容器对象,直接传入bar_label()即可自动识别每个块的中心位置标注对应数值
  • 数值为0的分段(比如x=B位置的第二层数值为0)不会生成冗余标签,符合常规展示需求
  • 如果需要调整标签的字号、颜色、偏移量,可以传入对应参数,比如plt.bar_label(p1, fontsize=12, color='white', padding=3)就能实现白色标签、字号12、向内偏移3像素的效果

内容的提问来源于stack exchange,提问作者Artyom P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:45:03