Camille
Camille

Reputation: 31

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 ?

Upvotes: 0

Views: 51

Answers (2)

Stef
Stef

Reputation: 30579

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

Upvotes: 3

In case, you know where you want to have your ticks, and you don't need to define too many, one of the easiest solutions could be to define them manually.

To achieve this, incorporating something like this into your code should work:

fig, ax = plt.subplots()
#...
    ax.set_xlim(0, max(distance_tour)) #setting the x-axis limits
    xticks = [0, 5000, 10000, 15000]  # Example positions, define which ticks you want to have based on your data
    xticklabels = ['19h03', '21h05', '22h7', '0h43']  # Example labels, set them according to the values set for xticks
    ax.set_xticks(xticks)
    ax.set_xticklabels(xticklabels)
#...
plt.show()

Upvotes: 0

Related Questions