如何为双变量堆叠柱状图的类别添加连接线?
给堆叠柱状图添加类别间连接线的实现方法
你可以在原有绘图代码的基础上,通过获取每个堆叠柱子的位置与高度数据,手动绘制出类别间的连接线,具体代码如下:
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
相关产品推荐
相关产品推荐

