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

如何修正Python代码使Matplotlib图表X轴标签正确显示?

解决Matplotlib子图X轴标签显示异常问题

你遇到的问题核心是混用了全局plt函数和子图对象ax的方法。因为代码里用的是子图ax = axs[i],全局plt的设置不会精准作用到这个子图上,导致X轴标签的刻度、旋转等设置失效。

修正后的代码如下:

ax = axs[i]
ax.plot(data.X_displacement, data.X_stiffness_force, color='steelblue', label='X_stiffness_forces')
ax.plot(data.Y_displacement, data.Y_stiffness_force, color='orange', label='Y_stiffness_forces')
ax.plot(data.Z_displacement, data.Z_stiffness_force, color='purple', label='Z_stiffness_forces')
# 替换所有plt.xxx为ax.set_xxx或ax.xxx方法
ax.set_ylabel('Stiffness force, in N')
ax.set_xlabel('Displacement, in m')
# plt.legend(bbox_to_anchor =(0.75, 0.25))
ax.set_xticks([-0.025, -0.020, -0.015, -0.010, -0.005,  0, 0.005, 0.010, 0.015, 0.020, 0.025])
ax.set_xlim(-0.025, 0.025)
ax.tick_params(axis='x', labelrotation=90)
ax.set_yticks([-0.006, -0.005, -0.004, -0.003, -0.002, -0.001, 0, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006])
ax.set_ylim(-0.006, 0.006)

关键修改点:

  • 将plt.ylabel/plt.xlabel替换为ax.set_ylabel/ax.set_xlabel
  • 将plt.xticks/plt.yticks替换为ax.set_xticks/ax.set_yticks
  • 将plt.xlim/plt.ylim替换为ax.set_xlim/ax.set_ylim
  • 保留ax.tick_params(本身就是子图对象的方法)

这样所有设置都会直接作用到你指定的子图ax上,X轴标签就能按照预期显示为-0.025到0.025、间隔0.005且旋转90度的样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:47:30