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

如何在pandas堆叠柱状图中为每个柱子的分段单独显示阈值边界?

堆叠柱状图各分段阈值标记实现方案

堆叠柱状图的每个分段的起始高度是前面所有类别数值的累加和,我们只需要计算每个类别分段的起始高度,加上对应阈值得到阈值线的y坐标,在每个柱子对应区间绘制水平线即可。

import pandas as pd
import matplotlib.pyplot as plt

# 初始化数据
data = {"A":[10,9], "B":[4,3],"C":[0,4]}
df = pd.DataFrame(data=data, index= ["Jan", "Feb"])
borders = {"A": 8, "B":4, "C": 3}

# 绘制基础堆叠柱状图
ax = df.plot(kind="bar", stacked=True, figsize=(16,9))
for c in ax.containers:
    ax.bar_label(c, label_type='center')

# 获取基础参数
x_pos = [tick.get_position()[0] for tick in ax.get_xticklabels()]
bar_width = ax.patches[0].get_width()
cols = df.columns.tolist()
# 计算每个类别分段的底部高度
cum_bottom = df.cumsum(axis=1).shift(axis=1, fill_value=0)

# 逐类别逐柱子绘制阈值线
for col_idx, col in enumerate(cols):
    current_threshold = borders[col]
    # 取当前类别柱子的颜色,保持视觉统一
    line_color = ax.containers[col_idx].patches[0].get_facecolor()
    for month_idx, x in enumerate(x_pos):
        # 计算阈值线y坐标
        y = cum_bottom[col].iloc[month_idx] + current_threshold
        # 绘制阈值虚线
        ax.hlines(
            y=y,
            xmin=x - bar_width/2,
            xmax=x + bar_width/2,
            color=line_color,
            linewidth=3,
            linestyle="--"
        )
        # 可选:添加阈值数值标签
        # ax.text(x, y, f"阈值:{current_threshold}", ha="center", va="bottom", fontsize=10)

plt.show()

补充说明

  • 阈值线默认和对应分段颜色一致,用虚线样式区分,长度刚好覆盖对应柱子
  • 若需要显示阈值数值,取消注释代码中text相关的行即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:54:04