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

Python如何在坐标轴标记点?为X轴添加自定义刻度点的方法

给X轴添加指定刻度点的实现方法

你可以通过matplotlib的set_xticks()和set_xticklabels()方法手动指定X轴刻度,以下是修改后的完整代码:

import pandas as pd
import matplotlib.pyplot as plt

# 确保日期索引为datetime类型(若未转换先执行这行)
# results_df.index = pd.to_datetime(results_df.index)

slope_fig, slope_ax = plt.subplots(figsize=(20, 8))
results_df.filter(like='Slope').plot(ax=slope_ax, title=f'{title} Slope')
for crisis, start, end in crisis_periods:
    slope_ax.axvspan(start, end, color='grey', alpha=0.3)
    slope_ax.text(start, slope_ax.get_ylim()[1], crisis, rotation=90, verticalalignment='top')

# ------------------- 添加指定刻度的核心代码 -------------------
# 1. 生成2020-2024区间的自定义刻度点,比如每年年初
custom_ticks = pd.date_range(start='2020-01-01', end='2024-12-31', freq='YS')
# 若需要特定日期的刻度,可直接手动指定:
# custom_ticks = pd.to_datetime(['2020-03-01', '2021-06-01', '2022-09-01', '2023-12-01', '2024-03-01'])

# 2. 设置X轴刻度位置
slope_ax.set_xticks(custom_ticks)
# 3. 设置刻度显示标签(比如只显示年份,优化可读性)
slope_ax.set_xticklabels([dt.strftime('%Y') for dt in custom_ticks], rotation=45, ha='right')
# ---------------------------------------------------------

slope_ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
slope_ax.set_ylabel('Slope')
plt.tight_layout()  # 自动调整布局,避免标签被截断
plt.show()

关键说明:

  • freq='YS'表示每年的第一天,若要每年最后一天用freq='Y',按需调整即可
  • 自定义刻度无需和原索引的日期完全匹配,matplotlib会自动对齐到对应位置
  • rotation=45和ha='right'是为了避免刻度标签重叠,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:42:13