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

Matplotlib绘制pandas时间序列时x轴刻度仅显示第一个如何解决

解决方案

问题原因

pandas内置的plot方法对DatetimeIndex类型的索引会默认启用自动日期定位器,你在plot参数中传入的xticks会被该定位器规则覆盖,导致无法显示全部自定义刻度。

完整可运行代码

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

# 构造数据部分和你原有代码一致
np.random.seed(365)
rows = 24
start_date=datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
data = np.random.uniform(2.1, 6.5, size=(rows, 1))
index = pd.bdate_range(start_date, freq='H', periods=rows)
df = pd.DataFrame(data=data, index=index, columns=['Ta']) #Ta: 室温

# 绘图部分
ax = df['Ta'].plot(
    figsize=(20,12),
    legend=True,
    ylim=(0,12),
    fontsize=10,
    grid=True,
    rot=0,
    xlim=(pd.Timestamp('2020-01-01 00:00:00'),pd.Timestamp('2020-01-01 23:00:00'))
)

# 显式设置x轴刻度和标签
ax.set_xticks(df.index)
# 自定义时间显示格式,这里可以按需调整,比如只显示小时就改成'%H:%M'
ax.set_xticklabels(df.index.strftime('%Y-%m-%d %H:%M'), fontsize=10)

plt.show()

可选优化

如果你不需要保留完整时间戳,只需要显示小时区分刻度,可以修改刻度标签格式简化显示:

ax.set_xticklabels(df.index.strftime('%H:%M'), fontsize=10)

如果需要保留原有subplots=True参数,只需要调整获取轴对象的逻辑即可:

axes = df['Ta'].plot(
    figsize=(20,12),
    legend=True,
    subplots=True,
    ylim=(0,12),
    fontsize=10,
    grid=True,
    rot=0,
    xlim=(pd.Timestamp('2020-01-01 00:00:00'),pd.Timestamp('2020-01-01 23:00:00'))
)
ax = axes[0]
ax.set_xticks(df.index)
ax.set_xticklabels(df.index.strftime('%Y-%m-%d %H:%M'), fontsize=10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:08