簡體   English   中英

更改 matplotlib 中 datetime.time 軸的格式

[英]Changing the formatting of a datetime.time axis in matplotlib

我試圖將 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 可以比time對象更容易處理datetime time對象。 您可以刪除.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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM