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

如何为双变量堆叠柱状图的类别添加连接线?

给堆叠柱状图添加类别间连接线的实现方法

你可以在原有绘图代码的基础上,通过获取每个堆叠柱子的位置与高度数据,手动绘制出类别间的连接线,具体代码如下:

import matplotlib.pyplot as plt
import pandas as pd

# 执行原有绘图逻辑,生成堆叠柱状图
ax = count[['new_category', "Count %", "Volume%"]].set_index('new_category').T.plot.bar(stacked=True) 
plt.xticks(rotation=360)

# 获取所有堆叠层的柱子容器
bars = ax.containers
# 计算每个x轴类别对应的中心坐标(确保连接线对齐柱子中心)
x_pos = [tick.get_x() + tick.get_width()/2 for tick in ax.get_xticklabels()]

# 遍历每一层堆叠的柱子,绘制连接线
for i in range(len(bars)):
    # 获取当前层每个柱子的高度
    heights = [bar.get_height() for bar in bars[i]]
    # 计算当前层柱子的底部位置:第一层底部为0,上层底部是下层所有高度的总和
    if i == 0:
        bottoms = [0]*len(heights)
    else:
        bottoms = [sum([bars[j][k].get_height() for j in range(i)]) for k in range(len(heights))]
    
    # 整理当前层每个柱子的顶部、底部坐标
    top_coords = [(x_pos[k], bottoms[k] + heights[k]) for k in range(len(x_pos))]
    bottom_coords = [(x_pos[k], bottoms[k]) for k in range(len(x_pos))]
    
    # 绘制相邻类别间的顶部连接线
    for j in range(len(top_coords)-1):
        plt.plot([top_coords[j][0], top_coords[j+1][0]], [top_coords[j][1], top_coords[j+1][1]], color='gray', linestyle='-', linewidth=1)
    # 绘制相邻类别间的底部连接线
    for j in range(len(bottom_coords)-1):
        plt.plot([bottom_coords[j][0], bottom_coords[j+1][0]], [bottom_coords[j][1], bottom_coords[j+1][1]], color='gray', linestyle='-', linewidth=1)

plt.show()

关键说明:

  • ax.containers 能获取到所有堆叠层的柱子集合,每个集合对应一组同类型的柱子
  • x_pos 计算出x轴类别的中心坐标,保证连接线和柱子位置对齐
  • 你可以调整color、linestyle、linewidth参数,让线条样式匹配目标效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:55:16