python-3.xplotlyplotly.graph-objects

Add a Plotly Express trace to a Graph Objects go.Figure() with multiple traces?


I am trying to visualize timestamps from different pandas dataframes using plotly Graph Objects. After successfully adding traces as go.Scatter() plots, I would now like to add a px.timeline() plot as a trace. Is this generally possible?

Here is my code:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go


df=pd.read_json(file1.json)
df2=pd.read_json(file2.json)
df3=pd.read_json(file3.json)

fig = go.Figure(layout=layout)
fig.add_trace(
    go.Scatter(x=df.column1, y=df.column2, name='name1', mode='markers')
)
fig.add_trace(
    go.Scatter(x=df2.column1, y=df2.column2, name='name2', mode='markers')
)
fig.add_trace(
    go.Scatter(x=df3.column1, y=df3.column2, name='name3', mode='markers')
)
#### add px trace ###
fig.update_traces(marker_size=10)

fig.show()

This is working well so far. Now, I would like to add the px.timeline() plot as a trace to my figure. I tried:

fig.add_trace(
    px.timeline(df,x_start="column1",
                x_end="column2", y='column3')

This raises the Value Error:

ValueError: 
    Invalid element(s) received for the 'data' property of [...]

Is there a workaround to adding px.-Plots to a go.Figure() ?


Solution

  • Try including .data[0]

    fig.add_trace(
    px.timeline(df,x_start="column1",
                x_end="column2", y='column3').data[0])