python - 在 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 更改为我想要的格式?
解决方案
Matplotlib 可以datetime
比time
对象更容易处理 -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()
推荐阅读
- python - 如何根据单选按钮选择运行脚本?(Tkinter)
- kubernetes - 如何修复错误:用户无法在命名空间“default”中的 API 组“apps”中获取资源“deployments”?
- javascript - React:在组件中使用 QuerySelectorAll
- azure-log-analytics - Azure Log Analytics KQL - 收到的最后一个日志(最近的)
- javascript - 如何使用正则表达式突出显示文档中匹配的文本
- android - viewbindig 类不会在 onCreate 方法之外实例化
- java - 在方法中创建的对象不可用
- python - 如何使用空切片的默认值计算 torch.mean?
- java - 使用 java8 流转换 Map 中的元素列表
- docker - docker image rm 命令不起作用,只是停止