如何将 xtick 设置为一天中的特定时间

How to set xtick to specific hours of the day

我有一些数据具有半随机次日频率并持续几天,例如:

date=[03/08/2011 00:00:00, 03/08/2011 03:30:00, 03/08/2011 06:45:00, 03/08/2011 12:00:00, 
03/08/2011 15:30:00, 03/08/2011 20:15:00, 04/08/2011 00:00:00, 04/08/2011 04:30:00, 
04/08/2011 05:45:00, 04/08/2011 12:00:00, 04/08/2011 15:30:00, 04/08/2011 21:15:00, 
05/08/2011 00:00:00, 05/08/2011 06:00:00, 05/08/2011 12:00:00, 05/08/2011 15:30:00, 
05/08/2011 20:40:00, 06/08/2011 00:00:00, 06/08/2011 6:00:00, 06/08/2011 12:00:00]
data=[1,4,2,4,5,3,5,9,4,1,4,6,7,9,0,7,4,3,1,2]

我希望 xticks 显示每天或每 12 小时的每个开始,所以只显示标签:

03/08/2011 00:00:00,  03/08/2011 12:00:00,  04/08/2011 00:00:00,  04/08/2011 12:00:00, 05/08/2011 00:00:00,  
05/08/2011 12:00:00,  06/08/2011 00:00:00,  06/08/2011 12:00:00

到目前为止,我已经尝试使用 xticks 并尝试使用频率,但是它不是很可靠,因为它只需要多个日期,具体取决于频率设置。因此我想知道是否有办法指定可以显示哪些日期? 这是我目前使用的代码:

frequency = round(len(date)/4)
plt.xticks(np.arange(0,len(date),frequency)) 

matplotlib.dates 模块设置一个“定位器”

from matplotlib.dates import HourLocator

_, ax = plt.subplots(figsize=(16,4))
ax.plot(date, data)
ax.xaxis.set_major_locator(HourLocator([0,12]))