Matplotlib柱状图X轴标签错位缺失问题技术求助
问题解决:X轴标签位置跳变、显示不全的修复
问题根源
- 数据长度不匹配:你的
andar列表有16个标签,但ano_1到ano_5都是15组数据,两者数量不一致,导致标签和数据组无法一一对应。 - 未指定刻度位置:仅使用
ax.set_xticklabels()设置标签,但没定义刻度的位置,matplotlib会沿用默认的刻度位置,和自定义标签数量不匹配,最终出现标签跳变、部分显示的问题。
修复步骤
- 调整
andar列表长度,使其和数据组数量(15)一致,删除多余元素。 - 计算每组柱状图的中间位置,作为X轴刻度的放置点(5组柱状图的中间位置为
rects1 + 2*barWidth)。 - 先通过
ax.set_xticks()指定刻度位置,再用ax.set_xticklabels()设置对应标签。
修正后的完整代码
import numpy as np import matplotlib.pyplot as plt # 修正后的标签列表,和数据组数量一致(15个) andar = ['23º andar', '22º andar', '21º andar', '20º andar', '19º andar', '18º andar', '17º andar', '16º andar', '15º andar', '14º andar', '13º andar', '12º andar', '11º andar', 'Térreo A', 'Térreo B'] ano_1=[285, 107, 38, 61, 62, 93, 45, 68, 88, 60, 77, 61, 60, 457, 34,] ano_2=[336, 38, 24, 72, 64, 92, 52, 72, 94, 63, 80, 41, 65, 431, 45] ano_3=[277, 12, 21, 19, 38, 86, 37, 45, 68, 55, 61, 15, 43, 431, 27] ano_4=[261, 8, 2, 4, 46, 91, 33, 41, 61, 55, 55, 22, 41, 452, 21] ano_5=[222, 2, 2, 6, 46, 80, 33, 41, 63, 61, 57, 26, 39, 457, 14] barWidth = 0.14 # 柱状图宽度 fig, ax = plt.subplots(constrained_layout=True, figsize=(30, 12)) rects1 = np.arange(len(ano_1)) rects2 = [x + barWidth for x in rects1] rects3 = [x + barWidth for x in rects2] rects4 = [x + barWidth for x in rects3] rects5 = [x + barWidth for x in rects4] plt.bar(rects1, ano_1, width=barWidth, label = 2018) plt.bar(rects2, ano_2, width=barWidth, label = 2019) plt.bar(rects3, ano_3, width=barWidth, label = 2020) plt.bar(rects4, ano_4, width=barWidth, label = 2021) plt.bar(rects5, ano_5, width=barWidth, label = 2022) # 设置标签、标题和自定义X轴刻度 ax.set_ylabel('Consumo') ax.set_title('Consumo de energia por andar') # 关键:先设置刻度位置,放在每组柱状图的中间 ax.set_xticks(rects1 + 2*barWidth) # 设置对应标签,添加右对齐避免文字重叠 ax.set_xticklabels(labels = andar, rotation = 45, ha='right') ax.legend() fig.tight_layout() plt.show()
额外优化
添加ha='right'参数让标签右对齐,避免旋转后出现文字重叠,提升图表可读性。
内容的提问来源于stack exchange,提问作者Mateus Nascimento
相关产品推荐
相关产品推荐

