You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置Matplotlib图表的xticks 让最外侧x轴刻度不贴边居中

问题原因

你的x轴刻度设置到了10,但Matplotlib默认会根据已绘制的柱状图范围(最大柱的位置为9+0.2=9.2)自动适配x轴边界,导致x轴右边界刚好卡在10的位置,因此刻度10会紧贴图表边缘,无法和其他刻度一样居中显示。

解决方案

手动调整x轴的显示范围,给左右两侧各预留半个刻度单位的余量即可,在你的plt.xticks()代码后添加一行plt.xlim(0.5, 10.5)就可以实现效果。

修改后完整代码

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6,7,8,9])
y=[83.742,83.572,80.446,85.960,85.031,84.605,85.348,86.910,83.572]
z=[83.9901, 83.6721,80.2542,86.2601,84.9232,84.3019,85.4232,86.7565,84.5207]


plt.bar(x-0.2, y, width=0.4,label='Actual', color='g', align='center')
plt.bar(x+0.2, z, width=0.4,label='Predicted', color='b', align='center')
plt.ylim(60,95)
plt.legend(loc=2, prop={'size': 6.5})
labels=[1,2,3,4,5,6,7,8,9,10]
plt.xticks(labels,labels,rotation=60)
# 新增下面这行调整x轴范围
plt.xlim(0.5, 10.5)
str_x = [l for l in labels if not l in x]
for s_x in str_x:
    plt.text(s_x, 70, 'x', ha='center', fontsize=16,color='r')

plt.xlabel("Node no")
plt.ylabel("Accuracy (%)")

plt.show()

效果说明

调整后x轴左右边界分别为0.5和10.5,每个刻度值刚好位于对应区间的中心位置,最右侧的10刻度也会和其他刻度保持一致的居中效果,不会再紧贴边缘。

内容的提问来源于stack exchange,提问作者abaair davis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:45:05