[英]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.