Horizontal Stacked Bars Legend Behaviour

Hi, i’m having some issues with the legend behaviour in my graph.
This is my code:

def plot_stint_data(stint_data, team_mapping, pit_stop_losses):
    fig = go.Figure()

    # Define a color list for stints
    color_list = [
        'rgba(255, 99, 71, 0.7)',   # Stint 1 - Tomato
        'rgba(54, 162, 235, 0.7)',  # Stint 2 - Sky Blue
        'rgba(75, 192, 192, 0.7)',  # Stint 3 - Light Green
        'rgba(153, 102, 255, 0.7)', # Stint 4 - Lavender
        'rgba(255, 159, 64, 0.7)',  # Stint 5 - Orange
        'rgba(255, 205, 86, 0.7)'   # Stint 6 - Light Yellow
    ]
    
    y_labels = [team_mapping[car_id] for car_id in stint_data.keys()]

    for i, (car_id, team_name) in enumerate(zip(stint_data.keys(), y_labels)):
        stint_info = stint_data[car_id]
        stint_lengths = [stint['num_laps'] for stint in stint_info]
        medians = [stint['median'] for stint in stint_info]
        mads = [stint['mad'] for stint in stint_info]
        pit_losses = pit_stop_losses.get(car_id, [])  # Get pit stop losses, or empty list if none available

        start_pos = 0  # This will track the left (start) position for the stacked bars
        for j, (length, median, mad) in enumerate(zip(stint_lengths, medians, mads)):
            color = color_list[j % len(color_list)]  # Loop through color_list
            formatted_median = format_time(median)
            pit_loss = pit_losses[j] if j < len(pit_losses) else None
            is_last_stint = (j == len(stint_lengths) - 1)

            text = f"<b>{length}</b> laps {formatted_median} <> {2*(mad):.2f}"
            hovertext = f"Stint {j + 1}<br>MAD RANGE: {formatted_median}<>{2*(mad):.2f}<br>Length: {length} laps"

            if not is_last_stint and pit_loss is not None:
                text += f" (Pit Loss: {pit_loss}s)"
                hovertext += f"<br>Pit Loss: {pit_loss}s"
            
            fig.add_trace(go.Bar(
                y=[team_name],  # Use the team name for the y-axis label
                x=[length],  # Bar width corresponds to the stint length
                name=team_name,  # Use team name in the legend
                orientation='h',
                text=[text],  # Include pit stop loss only if it's not the last stint
                textposition='inside',  # Position the text inside the bar
                textfont=dict(size=14),
                hoverinfo='text',
                hovertext=hovertext,  # Include pit stop loss in hovertext unless it's the last stint
                marker=dict(color=color, line=dict(color='black', width=1)),  # Set color from color_list
                legendgroup=team_name,  # Group stints by car/team
                showlegend=(j == 0),  # Only show legend for the first stint of each car
                
            ))
            start_pos += length  # Increment start_pos to stack the next stint
    
    fig.update_layout(
        barmode='stack',
        title='Car Stints with Median, MAD, and Pit Stop Losses',
        xaxis_title='Number of Laps',
        yaxis=dict(
            tickvals=list(range(len(y_labels))),
            ticktext=y_labels  # Use team names on the y-axis
        ),
        hoverlabel=dict(
            bgcolor="white",
            font_size=12,
            font_family="Arial"
        ),
        legend_title_text='Teams',  # Set legend title to Teams
    )
    
    fig.update_yaxes(autorange='reversed')
    
    # Return the HTML div and script for embedding
    return pio.to_html(fig, full_html=False)

and this is what happens:


when i toggle an item from the legend, it just removes the last trace group from the graph and not the tracegroup i’m toggling.
same thing happens if i don’t use legend group. it correctly hides the traces i toggle, but the moment i toggle the last trace for a group, it hides the last trace in the graph and displays back the group i was hiding