Plots with grouped legend

Is there a way to have a grouped legend? So instead of what I have below, you would see β€˜a’, β€˜b’, β€˜c’, β€˜d’ in the legend. And when each was pressed it would toggle the whole group off. (eg: if I clicked β€˜a’ it would toggle trace β€˜a_c’ and β€˜a_d’ off). I still need each trace to have its own unique color.

Any help would be really apreciated!

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame(
    {
        "type1": ["a", "a", "a", "b", "b", "b"],
        "type2": ["c", "d", "c", "d", "c", "d"],
        "value": [1, 2, 3, 4, 5, 6],
    }
)
fig = go.Figure()
for i, (type1, type2) in enumerate(
    df[["type1", "type2"]].drop_duplicates().itertuples(index=False)
):
    fig.add_trace(
        go.Scatter(
            x=df.query("type1 == @type1 & type2 == @type2").index,
            y=df.query("type1 == @type1 & type2 == @type2").value,
            name=f"{type1}_{type2}",
        )
    )
fig.show()

Hi @lspen, welcome to the forums. Something like this is possible, but has it’s limits.

the arguments you are looking for are legendgroup and legendgrouptitle

applied to your example:

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame(
    {
        "type1": ["a", "a", "a", "b", "b", "b"],
        "type2": ["c", "d", "c", "d", "c", "d"],
        "value": [1, 2, 3, 4, 5, 6],
    }
)
fig = go.Figure()
for i, (type1, type2) in enumerate(
    df[["type1", "type2"]].drop_duplicates().itertuples(index=False)
):
    fig.add_trace(
        go.Scatter(
            x=df.query("type1 == @type1 & type2 == @type2").index,
            y=df.query("type1 == @type1 & type2 == @type2").value,
            name=f"{type1}_{type2}",
            legendgroup=type1,
            legendgrouptitle={'text': type1}
        )
    )
fig.show()

creates:

Thanks for the quick reply! This would be perfect, except that I can’t toggle the individual traces. I’m guessing thats what you mean when you say this is limited?

Exactly, hiding only one trace out of a grouped legend is not possible. There are some requests on github for this, but it’s not implemented in the current version of plotly.

1 Like