Search code examples
matplotlibtimeformatticker

Chart with hh:min format in the horizontal axis instead of hours


I have an array that consist of two columns. One is for time and the second is for tension. I would like to plot tension on the vertical axis, and time on the horizontal axis. My time dataframe looks like this :

enter image description here

It ends with 45513,7941. I think it's in the excel format (not sure). The time data goes from 19h03 yesterday (so 7 pm 3 minutes) to 19h03 today. I would like to plot the horizontal axis origin as 19h03 (or 19:03 something like this) and the end as 19h03. In between i would like the graduation to be in this format too. How can i do this please ?


Solution

  • You have two possibilities:

    1. Subtract 25569 from the float values representing the Excel dates (25569 is the Excel value of the standard matplotlib epoch of '1970-01-01T00:00:00')
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
        import numpy as np
        
        arr = np.linspace(45512.7942, 45513.7941, 21)
        
        fig, ax = plt.subplots()
        ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.AutoDateLocator()))
        
        ax.plot(arr - 25569, range(len(arr)), 'x')
    
    1. Set the matplotlib epoch to '1899-12-30' which is the Excel epoch. Note that this must be done before any plotting. If in an interactive environment, restart it.
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
        import numpy as np
        
        mdates.set_epoch('1899-12-30')
        
        arr = np.linspace(45512.7942, 45513.7941, 21)
        
        fig, ax = plt.subplots()
        ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.AutoDateLocator()))
        
        ax.plot(arr, range(len(arr)), 'x')
    

    enter image description here