[英]Reformat matplotlib x-axis from HH:MM:SS to HH:SS
我有一天中每分鍾的數據點:
import numpy as np
data = np.random.random(1440,)
# I can represent minutes as integers:
mins = np.arange(1440,dtype=np.int)
# convert to datetime
import datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])
# and plot for every 20 samples:
import matplotlib.pyplot as plt
plt.plot(times[1::20], data[1::20])
給我:
如何將x軸格式更改為HH:MM?
我嘗試使用datetime.time()
函數而不是datetime.datetime()
但是這會導致錯誤。
您可以使用日期包中的自定義刻度格式化 程序來根據需要呈現日期。
擴展您的代碼示例:
import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates
data = np.random.random(1440,)
# I can represent minutes as integers:
mins = np.arange(1440,dtype=np.int)
# convert to datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])
# and plot for every 20 samples:
plt.plot(times[1::20], data[1::20])
# generate a formatter, using the fields required
fmtr = dates.DateFormatter("%H:%M")
# need a handle to the current axes to manipulate it
ax = plt.gca()
# set this formatter to the axis
ax.xaxis.set_major_formatter(fmtr)
plt.show()
格式字符串根據strftime
文檔定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.