将matplotlib的x轴格式从HH:MM:SS改为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])
这给了我:
我该如何把横轴的格式改成小时:分钟(HH:MM)呢?
我试着用 datetime.time()
函数来代替 datetime.datetime()
,但是这样会出错。
1 个回答
3
你可以使用来自自定义刻度格式器,这个格式器是属于日期包的,这样你就可以按照自己的需求来显示日期了。
下面是你代码示例的扩展:
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
文档。