How to avoid duplicate legend labels in plotly or pass custom legend labels

后端 未结 3 874
深忆病人
深忆病人 2021-01-11 15:32

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 15:57

    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.

提交回复
热议问题