Update bar charts

I have a dash application where I am filtering data and then plotting it with following code:

def filter_dataframe(selected_racetracks, selected_bops):
    filtered_df = df_bop.copy()  # Initialize with original DataFrame

    # Perform data filtering based on left-hand side filter
    filtered_df = filtered_df.loc[(filtered_df['racetrack'] == selected_racetracks[0])]

    # Check if selected_bops is None or empty list
    if not selected_bops[0] is None:
        filtered_df = filtered_df[filtered_df['bop'] == selected_bops[0]]

    # Get the first racetrack from the list
    racetrack_str = selected_racetracks[0] if selected_racetracks else None
    # Check if the filtered DataFrame is empty
    if filtered_df.empty:
        # Return an empty figure if the filtered DataFrame is empty
        return {'data': [], 'layout': {}}
    # ==================== Figure 1 ================================
    fig_weight = px.bar(
        filtered_df,
        x='make_model',
        y='total_weight_wo_driver',
        barmode='group',
        color='bop_date',
        template="plotly_dark",
        text="total_weight_wo_driver",
    )


    # Additional traces for the second and third rows of filters
    for racetrack, bop in zip(selected_racetracks[0:], selected_bops[0:]):
        if racetrack and bop:
            filtered_df_additional = df_bop[(df_bop['racetrack'] == racetrack) & (df_bop['bop'] == bop)]
            date_string = datetime.strptime(filtered_df_additional['bop_date'].unique()[0], '%Y.%m.%d').strftime('%Y.%m.%d')
            bar_text = filtered_df_additional['total_weight_wo_driver']
            if not filtered_df_additional.empty:
                fig_weight.add_bar(
                    x=filtered_df_additional['make_model'],
                    y=filtered_df_additional['total_weight_wo_driver'],
                    name=date_string,   # set trace name
                    text=bar_text
                )


    fig_weight.update_xaxes(
        tickangle=-70)

    fig_weight.update_layout(
        title_text=racetrack_str + " BOP total weight evolution",
        title_xanchor="left",
        barmode='group',
        yaxis_range=[1200, 1400],
        height=600,
        title_font=dict(size=24)
    )

    return fig_weight

My problem is that, when I am using the Addition traces part, everything is working fine but the generated bar charts are overlaying the first chart, like you can see below:

Are there any usefull hints in solving this issue?

I have tried to generate the figure directly within the loop, but then I am getting an error that the graph can not be done.

Thank you for the help!

With massive help from ChatGPT I have a solution for my problem:

def filter_dataframe(selected_racetracks, selected_bops):
    # Initialize an empty figure data list
    fig_data = []
    # Define a color map for unique bop_dates
    color_map = {}
    # Perform data filtering based on selected filters
    for i, (racetrack, bop) in enumerate(zip(selected_racetracks, selected_bops)):
        if racetrack and bop:
            filtered_df = df_bop[(df_bop['racetrack'] == racetrack) & (df_bop['bop'] == bop)]
            if not filtered_df.empty:
                # Create a new bar chart for each filter combination
                fig_weight = px.bar(
                    filtered_df,
                    x='make_model',
                    y='total_weight_wo_driver',
                    barmode='group',
                    color='bop_date',
                    template="plotly_dark",
                    text='total_weight_wo_driver',
                    width=1600
                )
                # Assign a unique color for each bop_date category
                for date in filtered_df['bop_date'].unique():
                    if date not in color_map:
                        color_map[date] = px.colors.qualitative.Plotly[i % 10]  # Choose color from Plotly qualitative palette

                # Map bop_date to color
                # filtered_df.loc[:, 'color'] = filtered_df['bop_date'].map(color_map)
                filtered_df = filtered_df.assign(color=filtered_df['bop_date'].map(color_map))

                fig_weight.update_traces(marker=dict(color=filtered_df['color']))
                fig_weight.update_xaxes(tickangle=-70)

                fig_weight.update_layout(
                    title_text=f"{racetrack} BOP total weight evolution",
                    title_xanchor="left",
                    yaxis_range=[1200, 1400],
                    height=600,
                    title_font=dict(size=24)
                )

                # Append the bar chart data to the list
                fig_data.append(fig_weight)

    # Combine all traces into a single figure
    combined_weight = fig_data[0].to_dict() if fig_data else {'data': [], 'layout': {}}
    combined_weight['data'] += [trace for fig in fig_data[1:] for trace in fig.to_dict()['data']]

    return combined_weight