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

如何在Pandas绘图中每月仅显示一个X轴刻度?

解决Pandas每日时间序列柱状图X轴仅显示每月刻度的问题

问题核心:使用plot(kind='bar')绘制每日数据时,Pandas会将日期索引转换为**整数位置(0,1,2...)**作为X轴坐标,而非保留日期时间戳。直接使用日期相关的定位器/格式化器会失效,因为这些工具默认处理时间戳,会把整数位置解析为1970年的起始时间。

可行解决方案

通过定位每月第一天对应的行位置,手动设置X轴刻度和标签:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 生成示例数据
periods = 100  # 跨3个多月的每日数据
date_range = pd.date_range(start='2023-01-01', periods=periods)
data = {
    'A': np.random.randint(1, 10, periods),
    'B': np.random.randint(1, 10, periods),
}
df = pd.DataFrame(data, index=date_range)

# 计算衍生列
df['total'] = df.sum(axis=1)
df['rolling'] = df['total'].rolling(3).mean()

# 绘制堆叠柱状图
ax = df[['A', 'B']].plot(kind='bar', stacked=True, figsize=(12, 6))

# 1. 筛选每个月的第一天日期
month_starts = df.index.to_series().groupby(df.index.to_period('M')).first()
# 2. 获取这些日期对应的行位置(bar图X轴的整数坐标)
tick_positions = [df.index.get_loc(date) for date in month_starts]
# 3. 设置刻度位置和标签
ax.set_xticks(tick_positions)
ax.set_xticklabels(month_starts.strftime('%b %Y'), rotation=45)

# 调整布局避免标签被截断
plt.tight_layout()
plt.show()

原理说明

  • 柱状图的X轴本质是数据的行索引位置(从0开始的整数),而非原始日期时间戳。
  • 先通过分组找到每个月的起始日期,再映射到对应的行位置,以此设置刻度点,最后将日期格式化为月份缩写 年份作为标签,完美避开1970年的解析问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:06:06