Home > Net >  How to format numerical labels into datetime labels on a plotly xaxis in python?
How to format numerical labels into datetime labels on a plotly xaxis in python?

Time:02-02

I have a plotly scatter plot like this example:

x = [1,2,3,4,5]
y = [3,2,3,5,6]

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))
fig.show()

Now I want to label the x-axis numbers as dates with this dates for example:

dates = pd.date_range('2022-01-01', periods=len(x), freq='1H')
dates.values

array(['2022-01-01T00:00:00.000000000', '2022-01-01T01:00:00.000000000', '2022-01-01T02:00:00.000000000', '2022-01-01T03:00:00.000000000', '2022-01-01T04:00:00.000000000'], dtype='datetime64[ns]')

How can i do this?

The Background here is that I want to add vlines or other things based on the numerical x axis I only want to show the labels as dates. Is this possible? Is the title of the question understandable?

CodePudding user response:

To change the tick to a date while keeping the x-axis already created alive, it is easiest to specify an x-value for the tick value and convert the tick string from a date to a string.

import plotly.graph_objects as go
import pandas as pd

x = [1,2,3,4,5]
y = [3,2,3,5,6]
dates = pd.date_range('2022-01-01', periods=len(x), freq='1H')

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))

fig.update_xaxes(tickvals=x, ticktext=[d.strftime('%Y-%m-%d %H:00') for d in dates])
fig.show()

enter image description here

  • Related