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

Matplotlib中如何隐藏Y轴首个刻度标签?

解决Matplotlib中仅隐藏Y轴首个刻度标签(保留刻度)的问题

我的Matplotlib绘图中Y轴首个标签(0.3)显示效果不佳,希望仅隐藏该标签,而非移除对应刻度。之前尝试了以下代码,但这会直接移除第一个刻度,无法满足需求:

y_ticks = ax.get_yticks() 
ax.set_yticks(y_ticks[1:])

正确解决方案

要实现只隐藏标签但保留刻度,需要单独修改刻度标签的文本内容,而非调整刻度位置。具体步骤如下:

  • 获取所有Y轴刻度标签对象,将第一个标签的文本设为空字符串;
  • 确保在所有绘图配置完成后执行该操作,避免Matplotlib自动更新刻度覆盖设置。

修正后的完整代码

plt.style.use('seaborn-v0_8-bright')
plt.rcParams.update({'font.size': 11, 'font.family': 'serif'})

fig, ax = plt.subplots(figsize=(10, 6))

ax.plot(specific_alpha_degrees, best_X_values, linestyle='-', marker='', label=r'$P_1$', color='blue')
ax.plot(specific_alpha_degrees, best_X_values2, linestyle='--', marker='', label=r'$P_2$', color='green')
ax.plot(specific_alpha_degrees, best_X_values3, linestyle='-.', marker='', label=r'$P_3$', color='red')
ax.plot(specific_alpha_degrees, best_X_values4, linestyle=':', marker='', label=r'$P_4$', color='purple')
ax.plot(specific_alpha_degrees, best_X_values5, linestyle='-', marker='', label=r'$P_5$', color='orange')

# 替换原来的错误代码,仅隐藏第一个Y轴刻度标签
ytick_labels = ax.get_yticklabels()
if ytick_labels:
    ytick_labels[0].set_text('')

ax.set_xlabel(r'Incline [$deg$]')
ax.set_ylabel(r'$x_{	ext{opt}}$')
ax.set_xlim(min(specific_alpha_degrees)-1, max(specific_alpha_degrees)+1)
ax.grid(True, which='major', linestyle='--', linewidth=0.5)
ax.minorticks_on()

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize='medium', frameon=False, framealpha=0.9, borderpad=1)

ax.spines['left'].set_position(('data', 0))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_color('black')
ax.spines['left'].set_color('black')

fig.tight_layout()  

plt.show()

另一种等价写法

也可以直接生成刻度标签列表,将第一个元素设为空:

y_ticks = ax.get_yticks()
ytick_labels = ['' if i == 0 else str(tick) for i, tick in enumerate(y_ticks)]
ax.set_yticklabels(ytick_labels)

内容的提问来源于stack exchange,提问作者Márton Horváth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:53:20