Search code examples
pythonplotly

How to eliminate duplicate legends in Plotly with subplot (Python)?


The following codes generate 2 plotly charts and lay them out in subplots. Each subplot contains legends that partially overlap with another subplot. As a result, there are duplicated legends on the right. Does anyone know a better way to eliminate duplicated legends in this situation? Thanks.

import plotly.graph_objects as go
from plotly.subplots import make_subplots

f1 = go.Figure([
    go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="A"),
    go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], name="B")
])
f2 = go.Figure([
    go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 5, 4, 5], name="B"),
    go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 1, 2, 1], name="C")
])

fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])

for ea in f1.data:
    fig.add_trace(ea, row=1, col=1)
    
for ea in f2.data:
    fig.add_trace(ea, row=1, col=2)
    
fig.show()

enter image description here


Solution

  • There may be several ways to do this, but the easiest is to set the second graph to specify the color and hide the legend.

    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])
    
    fig.add_trace(go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="A", legendgroup='A'), row=1, col=1)
    fig.add_trace(go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], name="B", legendgroup='B'), row=1, col=1)
    
    fig.add_trace(
        go.Scatter(
            x=[1, 2, 3, 4, 5],
            y=[1, 2, 5, 4, 5],
            line=go.scatter.Line(color='#EF553B'),
            name="B",
            legendgroup='B',
            showlegend=False
        ), row=1, col=2)
    fig.add_trace(
        go.Scatter(
            x=[1, 2, 3, 4, 5],
            y=[5, 4, 1, 2, 1],
            line=go.scatter.Line(color='#00cc96'),
            name="C",
            legendgroup='C',
            showlegend=True
        ), row=1, col=2)
    
    fig.show()
    

    enter image description here

    legend 'B' toggle

    enter image description here