Search code examples
pythondatetimemilliseconds

How to plot only the first millisecond digit of a datetime array


I have a datetime array that includes milliseconds. I plot the time only using:

formatterTime = '%H:%M:%S.%f'
ax0.xaxis.set_major_formatter(formatterTime)

However, the datetime array has 6 digits for milliseconds which is plotted as '11:45:05.100000', and I only want 1 millisecond digit, such as '11:45:05.1'.

I've tried suggestions such as

.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

but this only seems to work when printing the datetime to a string.

Is there a way of displaying only the first millisecond digit on the plot, without amending the original date array?


Solution

  • You can use FuncFormatter to set your own format. See this example (with some fake data):

    from matplotlib.ticker import FuncFormatter
    from matplotlib.dates import num2date
    
    x = pd.date_range("2020-01-01", periods = 10, freq = "131ms")
    y = range(10)
    
    fig, ax = plt.subplots()
    
    def foo(a, b):
        t = num2date(a)
        ms = str(t.microsecond)[:1]
        res = f"{t.hour:02}:{t.minute:02}:{t.second:02}.{ms}"
        return res
    
    ax.xaxis.set_major_formatter(FuncFormatter(foo))
    
    ax.plot(x, y)
    

    The result is:

    enter image description here