How to merge/collapse legend lines that are in the same legend group

Hi,

I’m plotting data with time-based events displayed as vertical lines and I want to show them in the legend.
Currently, each line has its own legend, which make the legend too big and unreadable.
I’ve already grouped them but there doesn’t seem to be a way to collapse or merge all these legends into a single one.

Here’s my graph for example:

Any help is appreciated!

Hey @PainOchoco welcome to the forums.

We had a similar question a while ago:

Thanks for the quick response, unfortunately your solution below doesn’t work as I wanted.

If you don’t want to see all the traces (vlines) you couls set showlegend=False to all but one trace.

It’s indeed displaying one line per legend group but if you click on the legend line, it toggles only the first shape of the group and not all of them.
There’s no way to collapse a legend group? That would be awesome.

Hi @PainOchoco you have two options:

Single traces, grouping into legendgroups

import numpy as np
import plotly.graph_objects as go

fig = go.Figure(
    go.Scatter(
        x=np.arange(10),
        y=np.random.randint(0,20,10),
        name='scatter'
    )
)

for i in range(1,9):
    fig.add_trace(
        go.Scatter(
            x=np.ones(2) * i,
            y=[0, 20],
            legendgroup="vertical",
            name=f"vertical_lines",
            mode="lines",
            line=dict(color="MediumPurple"),
            showlegend=[False, True][i==1]
        )
    )
    
fig.show()

Single trace, using None to “break” lines

fig = go.Figure(
    [
        go.Scatter(
            x=np.arange(10),
            y=np.random.randint(0,20,10),
            name='scatter'
        ),
        go.Scatter(
            x=[1,1,None,2,2,None,3,3],
            y=[0,20,None,0,20,None, 0,20],
            mode="lines",
        )
    ]
)

mrep legendgroup