✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🏦 Standard & Poor's chooses Dash Enterprise for ESG analysis. Learn why, sign up for the June 23 Webinar here!

Interject second legend group title into legend

I was trying to add a title for a second legend group in the base legend area. Since that is not currently a standard feature within plotly (as far as I know), I was trying to insert an annotation into the middle of the legend to act as a label for the 2nd group.

I cannot figure out how to put the annotation into the legend box … and have it move with the same coordinates as the legend when the browser window is resized.

I there a way to put the legend and an annotation in the same coordinate systems, and have them move together when browser is resized ?


import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1, 2, 3],
    y=[2, 1, 3],
    legendgroup="group",  # this can be any string, not just "group"
    name="first legend group",
    mode="markers",
    marker=dict(color="Crimson", size=10)
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3],
    y=[2, 2, 2],
    legendgroup="group",
    name="first legend group - average",
    mode="lines",
    line=dict(color="Crimson")
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3],
    y=[4, 9, 2],
    legendgroup="group2",
    name="second legend group",
    mode="markers",
    marker=dict(color="MediumPurple", size=10)
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3],
    y=[5, 5, 5],
    legendgroup="group2",
    name="second legend group - average",
    mode="lines",
    line=dict(color="MediumPurple")
))

main_title = 'legend grouping example'
fig.update_layout(title_text = main_title,
                    legend_title_text = 'Legend Group 1 Text',
                    legend_tracegroupgap= 60)


fig.add_annotation(xref='paper', yref='paper',
                        x=1.2, y=0.82,
                        text='Legend Group 2 Text',
                        showarrow=False)

fig.show()