如何调整Matplotlib分组柱状图的组间距与图表高度?
解决Matplotlib分组柱状图组内间距过小及图表高度不足的问题
我看了你的代码,确实存在组内柱子紧贴、图表高度不够导致标签拥挤的问题,下面是调整后的代码,我会标注关键修改点:
import matplotlib import matplotlib.pyplot as plt import numpy as np labels = ['Control \n Method 1', 'Method without\n coordination 1', 'Control \n Method 2', 'Control \n Method 3', 'Control \n Method 4' , 'Control \n Method 5'] ed_means = [20, 34, 30, 35, 27, 3] srdp_means = [25, 32, 34, 20, 25, 3] x = np.arange(len(labels)) width = 0.35 # 修改:稍微增大柱子宽度,为组内间距预留空间 # 修改:设置图表尺寸,(宽度, 高度),解决高度不足问题 fig, ax = plt.subplots(figsize=(14, 7)) # 修改:调整柱子的位置偏移量,从width/2改为width*0.6,让组内柱子间产生空隙 rects1 = ax.bar(x - width*0.6, ed_means, width, label='ED') rects2 = ax.bar(x + width*0.6, srdp_means, width, label='SRDP') ax.set_ylabel('Optimality in %', fontsize=12) ax.set_title('Scores by group and gender', fontsize=14) ax.set_xticks(x) ax.set_xticklabels(labels, fontsize=12, ha='center') # 确保标签居中对齐 ax.tick_params(axis='both', which='major', labelsize=12) ax.legend(fontsize=12) def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom', fontsize=10) autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show()
关键修改说明:
- 图表高度调整:通过
figsize=(14,7)自定义图表的宽高,这样不仅解决了高度不足的问题,也让x轴的多行标签显示更清晰,不会互相重叠。 - 组内柱间距调整:原来的柱子位置是
x ± width/2,导致两个柱子完全紧贴(左边柱子的右端点正好是右边柱子的左端点)。我把偏移量改成width*0.6,这样两个柱子之间就会留出0.2*width的空隙,同时稍微增大width保证柱子不会太细。 - 额外优化了部分文字的字体大小,让整体视觉效果更协调。
内容的提问来源于stack exchange,提问作者PeterBe
相关产品推荐
相关产品推荐

