You need to enable JavaScript to run this app. 使用matplotlib绘图时如何让X轴同时显示日期和时间而非仅显示日期
优惠活动
大模型
产品
解决方案
定价
更多

使用matplotlib绘图时如何让X轴同时显示日期和时间而非仅显示日期

解决方法

问题根因

你当前的异常来自两个常见配置问题:

  1. 日期格式化配置仅包含日期维度,没有配置时间显示规则
  2. 若date列未转为标准datetime类型,matplotlib无法识别时间精度,会将同日期的所有样本映射到同一个X轴位置

方案1:X轴同时显示日期+时间

先确保date列转为datetime类型,再修改日期格式化规则,按需调整X轴刻度间隔避免标签重叠:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mpl_dates

# 第一步:将date列转为标准datetime格式,必须执行
df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M')
x = df['date']
y = df['class']

plt.plot_date(x, y, linestyle='solid')
# 调整X轴标签旋转角度避免重叠
plt.gcf().autofmt_xdate(rotation=45)
# 格式化规则添加时间维度,可按需调整显示精度
date_format = mpl_dates.DateFormatter('%d-%m-%Y %H:%M')
plt.gca().xaxis.set_major_formatter(date_format)
# 可选:设置X轴刻度间隔,比如每3小时显示一个刻度,可根据样本密度调整interval值
plt.gca().xaxis.set_major_locator(mpl_dates.HourLocator(interval=3))

plt.tight_layout()
plt.show()

方案2:按日期+时间分箱聚合后展示

如果样本密度过高,直接展示所有时间点过于拥挤,可以按固定时间窗口分箱聚合后再绘图:

# 先完成date列转datetime的步骤
df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M')
df = df.set_index('date')
# 按2小时分箱,取class的均值作为聚合结果,可替换为max/min/count等聚合规则
# 时间窗口可按需调整:'1H'=1小时、'6H'=6小时、'12H'=半天
df_resampled = df.resample('2H').mean().reset_index()

x = df_resampled['date']
y = df_resampled['class']

# 后续绘图逻辑和方案1一致,可按需调整格式化规则
plt.plot_date(x, y, linestyle='solid')
plt.gcf().autofmt_xdate(rotation=45)
date_format = mpl_dates.DateFormatter('%d-%m-%Y %H:%M')
plt.gca().xaxis.set_major_formatter(date_format)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:27:03