One legend for 2 subplots with shared names

Is it possible to make one legend control two subplots with traces with shared names?

This is my current code and results, and I want to get a legend without repeated names.

##rewards
i=0
for agent in df.agent_id.unique():
    
    df_ag=df.loc[df['agent_id']==agent]
    df_ag.sort_values(by=['round'])
    fig.add_trace(go.Scatter(x=df_ag['round'], y=smoothTriangle(df_ag['performance'],smooth_degree),name='agent '+str(i)),1,1)
    i=i+1

df2=pd.read_sql_query("select performance, round from sg_models",conn)
df2.sort_values(by=['round'])
fig.add_trace(go.Scatter(x=df2['round'], y=smoothTriangle(df2['performance'],smooth_degree),name='Global'),1,1)

##losses
i=0
for agent in df.agent_id.unique():
    
    df_ag=df.loc[df['agent_id']==agent]
    df_ag.sort_values(by=['round'])
    fig.add_trace(go.Scatter(x=df_ag['round'], y=smoothTriangle(df_ag['performance'],smooth_degree),name='agent '+str(i)),1,2)
    i=i+1

df2=pd.read_sql_query("select performance, round from sg_models",conn)
df2.sort_values(by=['round'])
fig.add_trace(go.Scatter(x=df2['round'], y=smoothTriangle(df2['performance'],smooth_degree),name='Global'),1,2)

The desired results would look like this:
image

where if clicking in “agent 0” for example, would hide all the lines in both subplots but agent0 lines.

Hi @jab879,

you can group your legend items, see here:

One other approach is using the plotly.express (imported as px below) wrapper and reorganizing your dataframe accordingly if necessary. Plotly express will do the grouping for you and your code will look much shorter and cleaner.

The last line could look like something like this:

fig = px.line(df, x=‘Rounds’, y=‘Reward’, facet_col=‘Performance’, color=‘agent’)

if you provide some data sample I could help you more in detail

hope this helps, Alex-