✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Plotly Subplots using add_trace

Currently I have a plot that works individually:

traces = {}
for col in tickers:
    traces[col] = go.Scatter(x=x,
                             y=df[col] * 100,
                             name=col,
                             mode='lines',
                             line=dict(width=0.5),
                             stackgroup='one'
                             )

data = list(traces.values())
fig = go.Figure(data)

As you can see, I am iterating over the df and creating each go.Scatter as traces and as a result, I used go.Figure to contain all the data.

I would like to place this graph in other group of plotly graphs where I used subplots as follows:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = go.Figure()

fig = make_subplots(
    rows=3, cols=1,
    # shared_xaxes=True,
    vertical_spacing=0.03,
    specs=[[{"type": "table"}],
           [{"type": "scatter"}],
           [{"type": "scatter"}],
           ]
)

# PLOT 1 ==================================================================== #
fig.add_trace(
    go.Table(
        header=dict(
            values=["Portfolio", "Expected Return", "Expected Volatility",
                    "Sharpe Ratio"],
            font=dict(size=10),
            align="left"
        ),
        cells=dict(
            values=table_ports,
            align="left")
    ),
    row=1, col=1
)

# PLOT 2 ==================================================================== #
# mark the tickers position
fig.add_trace(go.Scatter(
    x=annual_volatility,
    y=annual_return,
    mode="text+markers",
    marker=dict(
        size=16,
    ),
    text=tickers,
    textposition="bottom center"
), row=2, col=1)

The problem is here. I am adding the plots to the subplots using fig.add_trace and the previous plot that I would like to add uses the fig = go.Figure(data) .

how can I use that fig.add_trace to contain all the traces created previously to create graph, and place it at row=3, col=1 ?

Hi @roro, welcome to the forum! You can use fig.add_traces to add several traces at once, like in the example below

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x='total_bill', y='tip', color='day')
from plotly.subplots import make_subplots
fig2 = make_subplots(1, 2)
fig2.add_traces(fig.data, rows=[1,]*len(fig.data), cols=[1,]*len(fig.data))
fig2.show()