Search code examples
pythonplotlyplotly-express

How to show 'hour precision' on datetimes in Plotly express?


I've looked-up answers on all blogs in vain ... I'm simply looking for a way to show datetimes with hour precision on my graphs. Here's an example of what my code generates :

My 'Start Date' & 'End Date' are normally on the following format 'mm-dd-yyyy H-M-S' however it won't show the hour precision until I zoom-in enter image description here

I know the question sounds stupid, but if you can point me in the right direction I would be grateful

Edit :

enter image description here


Solution

  • It is a case of setting xaxis_tickformat. without this sample below will behave as you described, no hour precision

    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    # for hour slots randonly assign a task
    df = pd.DataFrame({"Start": pd.date_range("1-jan-2021", periods=10**3, freq="4H")}).assign(
        End=lambda d: d.Start + pd.Timedelta(hours=1),
        Task=np.random.choice([f"Task {i}" for i in range(2)], 10**3, p=(0.8, 0.2)),
    )
    
    # compress consequetive rows
    df = df.groupby(df.Task.ne(df.Task.shift()).cumsum()).agg(
        {"Start": "min", "End": "max", "Task": "first"})
    
    fig = px.timeline(df, x_start="Start", x_end="End", y="Task", color="Task")
    
    fig.update_layout(xaxis_tickformat = '%Y-%m-%d %H:%M')
    

    change just hover template not overall axis

    fig = px.timeline(df, x_start="Start", x_end="End", y="Task", color="Task")
    print(fig.data[0].hovertemplate) # just FYI so can see what default template is
    fig.update_traces(hovertemplate="Task=%{y}<br>Start=%{base|%Y-%m-%d %H:%M}<br>End=%{x|%Y-%m-%d %H:%M}<extra></extra>")