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

如何将Matplotlib的X轴刻度替换为axvline下方的自定义标签

问题:替换陀螺仪图表X轴刻度为事件标签

我有一个正常运行的陀螺仪信息展示脚本,通过散点大小变化(代表角速度)来呈现欧拉角。当前X轴显示时间步刻度,我想隐藏原有刻度,替换为对应axvline事件标记的step1、step2等标签,已知如何隐藏X轴刻度,求如何把标签放到正确位置。

相关X轴代码如下:

scaling = 0.1
# x
ax1 = plt.subplot(gs[0,0:2]) # row span 2 columns
widths = np.absolute(df['avelo']['x'].iloc[start:end])
widths *= scaling
ax1.scatter(idx,df['angle']['x'].iloc[start:end],s=widths,c = 'blue')
for i in steplist:
        ax1.axvline(steps[i], linestyle = 'dashed', c = '0.8' )
ax1.axhline(0, linestyle = 'dashed', c = '0.8' ) 

解决方案

直接通过Matplotlib的set_xticks和set_xticklabels方法,将X轴刻度位置绑定到事件标记的时间步,同时设置对应标签即可。修改后的代码如下:

scaling = 0.1
# x
ax1 = plt.subplot(gs[0,0:2]) # row span 2 columns
widths = np.absolute(df['avelo']['x'].iloc[start:end])
widths *= scaling
ax1.scatter(idx,df['angle']['x'].iloc[start:end],s=widths,c = 'blue')

# 提取事件标记的位置并生成对应标签
step_positions = [steps[i] for i in steplist]
# 根据需求自定义标签,比如step1、step2...
step_labels = [f"step{idx+1}" for idx, _ in enumerate(steplist)]

# 绘制事件竖线
for pos in step_positions:
    ax1.axvline(pos, linestyle='dashed', c='0.8')

# 设置自定义X轴刻度
ax1.set_xticks(step_positions)
ax1.set_xticklabels(step_labels)

# 可选:如果标签出现重叠,添加旋转角度优化显示
# ax1.tick_params(axis='x', rotation=45, ha='right')

ax1.axhline(0, linestyle='dashed', c='0.8')

关键说明

  • set_xticks(step_positions):强制X轴刻度仅显示在事件标记对应的时间步位置
  • set_xticklabels(step_labels):为每个刻度位置设置自定义的stepN标签
  • 若标签过长或重叠,可通过tick_params调整旋转角度和对齐方式,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:10