消除Matplotlib堆叠柱状图(Stacked Barplot)中的柱子间隙
消除Matplotlib堆叠柱状图的柱子间隙
要消除堆叠柱状图的柱子间隙,核心是调整bar函数的宽度参数,并确保两层柱子的位置完全对齐:
关键修改点
- 给两次
bar调用都设置width=1,让柱子宽度占满分类标签的整个空间 - 如果x轴是字符串类型的分类值,建议先将其转换为数值索引,避免Matplotlib自动添加间隙
修改后的完整代码
import matplotlib.pyplot as plt import pandas as pd val1 = [2.20810623, 9.1243303, 9.78813997, 11.19015164, 13.71907402, 16.07695801, 20.60492477, 23.69439942, 25.23510585, 29.3574946] val2 = [70.6425054, 74.76489415, 76.30560058, 79.39507523, 83.92304199, 86.28092598, 88.80984836, 90.21186003, 90.8756697, 97.79189377] # 提取team A的分类标签并转为数值索引 team_a_source = df[df['team'] == 'A']['source'].tolist() x_indices = range(len(team_a_source)) fig, ax = plt.subplots() # 用数值索引定位,设置width=1消除间隙 ax.bar(x=x_indices, height=val1, label="A", width=1) ax.bar(x=x_indices, height=val2, label="B", bottom=val1, width=1) # 添加柱子内的数值标签 for bar in ax.patches: ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() / 2 + bar.get_y(), round(bar.get_height()), ha='center', color='w', weight='bold', size=10) # 还原x轴的分类标签 ax.set_xticks(x_indices) ax.set_xticklabels(team_a_source, rotation=90) ax.legend() ax.set_ylabel('percentage') plt.tight_layout() # 防止旋转后的标签被截断 plt.show()
说明
- 数值索引配合
width=1,让每个柱子完全填充分类标签对应的空间,彻底消除间隙 tight_layout()自动调整布局,避免x轴标签被截断
内容的提问来源于stack exchange,提问作者NeverSayEver
相关产品推荐
相关产品推荐

