Search code examples
pythonplotly

How to remove duplicate legends in plotly python when appending traces in a loop?


I have a script where I'm trying to plot the means of various dataframes in a loop, but they should share the same legend. Can anyone help me on how to remove the duplicates in this case?

column = 1
rowww = 1
fig = make_subplots(rows=3, cols=3)

i = 0
for disco in discos:

    df1 = meanOfModels(discosList[disco])
    df2 = meanOfModels(discosList[disco])

    print(rowww, column)


    fig.append_trace(go.Scatter(x=df1.index,
                            y=df1.mean(axis=1),
                            line=dict(color='blue'),
                            name='df1',
                            legendgroup='df1'),
                 row=rowww,
                 col=column)
    fig.append_trace(go.Scatter(x=df2.index,
                            y=df2.mean(axis=1),
                            line=dict(color='red'),
                            name='df2',
                            legendgroup='df2'),
                 row=rowww,
                 col=column)

    column += 1
    if column % 4 == 0:
       rowww += 1
       column = 1


fig.layout.update(title='Average Decrease in Ampacity (%)', showlegend=True)
fig.show()

enter image description here


Solution

  • Found a solution from an other thread, pasting it here.

    Keeping the rest of the code same, but adding this bit before fig.show() makes the duplicate legends disappear.

    names = set()
    fig.for_each_trace(
        lambda trace:
            trace.update(showlegend=False)
            if (trace.name in names) else names.add(trace.name))