Search code examples
pythonplotly

Python plotly axis has duplicated dates,


I have a plotly graph where the axis is dates made like this

fig = px.line(df, x='date', y='supply')
fig.update_layout(xaxis_tickformat = '%b %-d, %Y')

originally the axis labels had a time row 00:00 and 12:00 but I got rid of that because the date data doesn't have times in.

now the problem is there's 2 ticks for every date. I guess this is because it's using a datetime axis but there's no times. Getting rid of the time labels didn't really solve anything. how can I get 1 tick per date?

enter image description here


Solution

  • To control the number of ticks, you can use nticks(), which will let you select the number of ticks you want to display. Below is an example to demonstrate this... similar what you might have.

    >> df
        supply  date
    0   75  2022-04-09
    1   75  2022-04-09
    2   75  2022-04-10
    3   75  2022-04-10
    4   78  2022-04-11
    5   78  2022-04-11
    6   81  2022-04-12
    7   81  2022-04-12
    8   81  2022-04-13
    9   81  2022-04-13
    

    Code

    fig = px.line(df, x='date', y='supply')
    fig.update_layout(xaxis_tickformat = '%b %-d, %Y')
    fig.update_xaxes(nticks=5) 
    

    Plot BEFORE

    enter image description here

    AFTER

    enter image description here