pythonpandasplotlyplotly-python

How to set Pandas column as the datetime x-axis in Plotly


I have three lists containing data to display via Plotly. The first column represents Epoch timestamps (with milliseconds) and the second and third columns are the series to plot.

I am trying to create the pandas dataframe correctly, to pass to Plotly.

So far I have this:

import pandas as pd

epoch=[1716591253000, 1716591254000, 1716591255000, 1716591256000]
series_1=[5,6,7,8]
series_2=[9,10,11,12]

df = pd.DataFrame(data=zip(epoch,series_1,series_2),columns=['Datetime','Series 1','Series 2'])

print(df)

But I am unsure how I tell pandas that the first column is the date time column and needs to be the x-axis when passed to Plotly.

I found these time series examples:

https://plotly.com/python/time-series/

but unfortunately they're loading pre-created data


Solution

  • Convert the column to datetime, then use it as the x-axis:

    import plotly.express as px
    
    df['Datetime'] = pd.to_datetime(df['Datetime'], unit='ms')
    
    fig = px.line(df, x="Datetime", y=["Series 1", "Series 2"], title="Time Series Data")
    fig.show()
    

    enter image description here