我每天都有数据点:
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()
,但这会导致错误。
答案 0 :(得分:3)
您可以使用custom tick formatter中的dates package来根据需要呈现日期。
扩展您的代码示例:
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
docs定义。