How can I avoid duplicate legend labels in subplots? One way I would go about it in matplotlib would be to pass custom legend labels to an legend object. I couldn\'t find an
This is a code snippet I came up with which avoids to set showlegend=False manually on each trace with a duplicate name.
names = set()
fig.for_each_trace(
lambda trace:
trace.update(showlegend=False)
if (trace.name in names) else names.add(trace.name))
fig.for_each_trace calls the passed function for each trace. The function keeps track of which legend names already occurred (via the set names, like @LucG proposed in a comment), and hides legend entries for duplicate (or triplicate, ...) names.
The code needs to be run after all traces have been added to the figure, and before it is shown.