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

如何在Matplotlib中强制显示X轴标签

解决Matplotlib中横轴标签不显示的问题

问题出在你的绘图高度过小(figsize=(5, 2.7)),默认的底部边距不足以容纳x轴标签,导致标签被图片边缘裁剪掉了。不需要切换到axes/subplot模式,用以下两种方法即可解决:

方法1:保存图片时自动调整边距

修改plt.savefig的参数,添加bbox_inches='tight',让Matplotlib自动调整绘图区域边距,确保所有元素都被包含:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 101)
y = 1 + x + 0.4 * np.random.random(len(x))

plt.figure(figsize = (5, 2.7))
plt.plot(x, y, 'b.')
plt.ylabel('y')
plt.xlabel('x')
plt.savefig("tmp.png", dpi=300, bbox_inches='tight')

方法2:手动设置底部边距

在保存图片前,用plt.subplots_adjust手动增加底部边距,数值可根据实际情况调整:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 101)
y = 1 + x + 0.4 * np.random.random(len(x))

plt.figure(figsize = (5, 2.7))
plt.plot(x, y, 'b.')
plt.ylabel('y')
plt.xlabel('x')
plt.subplots_adjust(bottom=0.2)  # 调整底部边距,0.2是相对值,可按需修改
plt.savefig("tmp.png", dpi=300)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:20:56