1

I am trying to plot some time intervals:

import matplotlib.pyplot as plt
plt.hlines(1,v1,v2)
myFmt = DateFormatter('%H:%M:%S')

ax.xaxis.set_major_formatter(myFmt)

ax.xaxis.set_major_locator(SecondLocator(interval=2000)) 

where

v1=numpy.datetime64('2017-09-13T05:12:56.089000000')
v2=numpy.datetime64('2017-09-13T11:51:30.089000000')

then I get: Result which is very nice. However, for readibility I would like to have the ticks on the round hours e.g. 05.00, 06.00 ... However, I still need to be accurate so I need to add in the plot the exact time of beginning and end with the same formatting. A general solution would be great since I may need to repeat the tricks with months and so on..

00__00__00
  • 4,834
  • 9
  • 41
  • 89

1 Answers1

2

In order to get hourly ticks, a SecondLocator is surely not the best choice. Instead use an HourLocator

import numpy as np
import matplotlib.dates as mdates
import matplotlib.pyplot as plt

v1=np.datetime64('2017-09-13T05:12:56.089000000')
v2=np.datetime64('2017-09-13T11:51:30.089000000')

plt.hlines(1,v1,v2)
myFmt = mdates.DateFormatter('%H:%M:%S')

plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().xaxis.set_major_locator(mdates.HourLocator()) 

plt.show()

Anno0tating is a bit harder, you need to convert the datetime64 to datetime to a number, such that it can be formatted with the same formatter as the axis. (For more on datetime conversions see e.g. this useful post)

t = lambda x: myFmt(mdates.date2num(x.astype('<M8[s]').item()))

plt.annotate(t(v1), xy=(v1, 1), xytext=(0, 10), textcoords='offset points', )
plt.annotate(t(v2), xy=(v2, 1), xytext=(0, 10), textcoords='offset points',ha="right" )

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712