首页 > 解决方案 > 在 matplotlib 中更改 datetime.time 轴的格式

问题描述

我正在尝试将 x 轴的格式更改为 %H:%M,而 xticklabel 全部变为 00:00。xs看起来如下:

[datetime.time(15, 8, 35), datetime.time(15, 8, 36), datetime.time(15, 8, 37)]

我尝试使用以下脚本:

import matplotlib.dates as mdate
import matplotlib.pyplot as plt

dates = ['15:08:35', '15:08:36', '15:08:37']
xs = [datetime.strptime(d, '%H:%M:%S').time() for d in dates]
ys = range(len(xs))

plt.gca().xaxis.set_major_formatter(mdate.DateFormatter('%H:%M'))
plt.gca().xaxis.set_major_locator(mdate.DayLocator())

# Plot
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()
plt.show()

图像看起来像这样: 请点击

如何将 xticklabel 更改为我想要的格式?

标签: pythondatetimematplotlib

解决方案


Matplotlib 可以datetimetime对象更容易处理 -objects。您可以删除.time(). 这段代码应该可以工作,我编辑了日期以显示轴上不断变化的 x 值。

import matplotlib.dates as mdate
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

dates = ["15:05:35", "16:08:36", "17:09:37"]
# remove .time() from strptime
xs = [datetime.strptime(d, "%H:%M:%S") for d in dates]

ys = range(len(xs))

plt.gca().xaxis.set_major_formatter(mdate.DateFormatter("%H:%M"))
plt.gca().xaxis.set_major_locator(mdate.DayLocator())

# show all x-values on the x-axis
plt.xticks(xs)
# Plot
plt.plot(xs, ys)

plt.show()

在此处输入图像描述


推荐阅读