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

如何用Matplotlib在X轴仅显示时间?代码异常问题排查

Matplotlib X轴仅显示时间的问题排查与解决

你想要用Matplotlib绘制X轴仅显示时间的图表,但修改后的代码未达到预期效果——预期X轴显示10:00到10:10的时间范围,实际结果不符。

你的代码如下:

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.HourLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

问题原因

核心错误是你将解析后的datetime对象调用了.date()方法,转换成了date对象——这会丢失所有时间(时/分/秒)信息。所有x值都变成了同一天的日期,没有时间维度的数据,导致HourLocator无法识别出不同的时间刻度,最终X轴无法正确显示预期的时间范围。

修正方案

去掉.date(),保留完整的datetime实例,同时根据数据的5分钟间隔调整刻度定位器,确保刻度匹配数据:

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
# 保留完整的datetime对象,不转换为date
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M") for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)
# 使用MinuteLocator,设置间隔为5分钟,匹配数据的时间间隔
locator = mdates.MinuteLocator(interval=5)
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

关键修正点

  1. 保留时间信息:不调用.date(),让x轴数据携带完整的日期+时间信息,Matplotlib才能正确解析时间刻度。
  2. 匹配刻度间隔:原代码用HourLocator会只显示整小时刻度,而你的数据是5分钟间隔,改用MinuteLocator(interval=5)可以精准显示10:00、10:05、10:10这些刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 09:14:59