2

My current code uses a for-loop to populate plotly line plots, generally with hundreds trends being added:

fig.add_trace(go.Scatter(
        x=x_axis_data,
        y=y_axis_data,
        mode='lines',
        legendgroup="Data Group 1",
        name='Data',
        line=dict(
            color='royalblue',
            dash ='dot',
            width=3.5,
        )
    ),row=1,col=j)   

Once all of my traces are added, I use the following (which I understand is the default setting anyway):

 fig.update_layout(showlegend=True)

My issue is that in the plot legend, I end up with a legend title for every trace when all I want is to show either:

1) unique trace names only (no duplicates), or 2) the legend group name (only 1 time each, not one per trend added).

Is there a way to do this without adding dummy traces, etc.? FYI, I have reviewed the following resource: https://plotly.com/python/legend/. This would work as-is if I was not using a for-loop to populate multiple traces with one fig.add_trace function, but I cannot get it to do what I want with the legend with the for-loop population. Thanks.

1
  • Do you mind to share a mcve?
    – rpanai
    Commented Jun 11, 2020 at 16:39

1 Answer 1

5

The way to do this is to state whether or not to show the legend inside your trace with whatever your condition is;

fig.add_trace(go.Scatter(
    x=x_axis_data,
    y=y_axis_data,
    mode='lines',
    showlegend=True if condition is True else False,
    legendgroup="Data Group 1",
    name='Data',
    line=dict(
        color='royalblue',
        dash ='dot',
        width=3.5,
    )
),row=1,col=j)

Stating whether or not to show the legend in your layout is absolute to the plot and not trace specific.

1
  • Thanks, this works. I just set a counter, and for the condition above, set it to true only for the first count.
    – ChrisCD
    Commented Jun 12, 2020 at 22:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.