Adding figures created in a loop to one main fig

Starting from the code below, how can I create a mainfig that contains exact copies of the figures created in the loop?

import sys
import datetime as dt
import numpy as np
import pandas as pd
import arcelormittal as am
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
from datetime import datetime
#create df
data = {'datum': [datetime(2023, 1, 1), datetime(2023, 1, 2), datetime(2023, 1, 3),
                  datetime(2023, 1, 4), datetime(2023, 1, 5), datetime(2023, 1, 6),
                  datetime(2023, 1, 7), datetime(2023, 1, 8), datetime(2023, 1, 9),
                  datetime(2023, 1, 10)],
        'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        'B': [11, 12, 20, 24, 15, 12, 17, 18, 19, 20],
        'C': [21, 22, 40, 24, 25, 26, 20, 28, 29, 30],
        'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40]}
df = pd.DataFrame(data)
# create plots
my_list=[['A', 'B'], ['C', 'D']]
mainfig = make_subplots(rows=2,cols=1)
for item in my_list:
    fig = px.line(df,x='datum', y=item)
    fig.show()

Hi @marvy

px.line() creates a Figure object. You will need to extract the traces (data) of this object. Since your y- argument is a list of length =2, you will have two traces.

Once you extracted the traces, you can add them to the mainfig to the corresponding row . Explicitly:

for idx, item in enumerate(my_list, start=1):
    fig = px.line(df,x='datum', y=item)
    extracted_traces = fig.data
    mainfig.add_traces(extracted_traces, cols=1, rows=idx)
mainfig.show()

I would plotly.graph_objects in first place instead of using plotly.epress however.