简体   繁体   中英

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

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?

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM