使用Matplotlib绘制分组柱状图时如何正确对齐柱子避免重叠
重叠错位的核心原因
你绘制分组柱状图时出现柱子重叠、对齐错位,本质是两个参数设置错误:
- 单根柱子宽度设置为0.35时,相邻柱子的水平间距仅为0.175(也就是width/2),间距比柱子本身宽度还小,必然会出现大面积重叠
- 四个柱子的排布没有以你预设的x轴刻度位置为中心对称对齐,整组柱子会出现视觉偏移
修正逻辑
分组柱状图的排布核心是以每个分类的x轴中心为中点,将同组内的多根柱子左右等距对称排列,相邻柱子的水平间距等于单根柱子的宽度,从根源上避免重叠。
针对你的4组线程数据,具体调整规则:
- 将单根柱子宽度调整为0.2,4根柱子总占宽0.8,在不同分类组之间预留足够留白,视觉上更清爽
- 四个柱子的水平偏移量以x轴刻度为中心对称设置,依次为
-1.5*width、-0.5*width、+0.5*width、+1.5*width,完全消除重叠
修正后的可运行代码
from matplotlib import pyplot as plt import numpy as np labels = ['tt.03', 'tt.03a', 'tt.06', 'stats.txt', 'sum.txt', 'minmax.txt'] fourthreads = [19.290, 17.861, 21.782, 49.188, 17.821, 75.593] threethreads = [23.447, 22.125, 27.251, 62.778, 22.769, 95.78] twothreads = [33.364, 31.793, 39.508, 89.716, 32.954, 137.475] onethreads = [61.1, 58.074, 72, 163.335, 61, 248.597] x = np.arange(len(labels)) width = 0.2 fig, ax = plt.subplots() # 按对称偏移逻辑排布柱子 rects1 = ax.bar(x - 1.5*width, onethreads, width, label='1 Threads') rects2 = ax.bar(x - 0.5*width, twothreads, width, label='2 Threads') rects3 = ax.bar(x + 0.5*width, threethreads, width, label='3 Threads') rects4 = ax.bar(x + 1.5*width, fourthreads, width, label='4 Threads') ax.set_ylabel('Execution time in seconds') ax.set_title('Execution time in seconds by thread and command') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): 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') autolabel(rects1) autolabel(rects2) autolabel(rects3) autolabel(rects4) fig.tight_layout() plt.show()
调整效果
- 每个分类下的4根柱子完全无重叠,整体居中对齐在对应的x轴刻度下方
- 原有数值标注功能完全保留,不会出现标注错位
- 柱子间距均匀,组与组之间留白充足,不会出现拥挤感
内容的提问来源于stack exchange,提问作者ermaion
相关产品推荐
相关产品推荐

