Skip to content

Commit e3ad1e7

Browse files
Hide unlabeled traces from legend when figure has a legend
1 parent e5d95bf commit e3ad1e7

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎plotly/matplotlylib/renderer.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,11 +447,15 @@ def draw_marked_line(self, **props):
447447
label = props["label"]
448448
# matplotlib uses "_nolegend_" and auto-generated "_childN"
449449
# labels for artists that must not appear in a legend
450-
if isinstance(label, str) and label.startswith("_"):
450+
if not label or (isinstance(label, str) and label.startswith("_")):
451451
label = None
452+
showlegend = False
453+
else:
454+
showlegend = None
452455
marked_line = go.Scatter(
453456
mode=mode,
454457
name=label,
458+
showlegend=showlegend,
455459
x=[xy_pair[0] for xy_pair in props["data"]],
456460
y=[xy_pair[1] for xy_pair in props["data"]],
457461
xaxis="x{0}".format(self.axis_ct),

‎plotly/matplotlylib/tests/test_renderer.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,23 @@ def test_no_legend_entries_for_internal_mpl_labels():
323323
assert all(t.name is None for t in plotly_fig.data)
324324

325325

326+
def test_unlabeled_traces_hidden_from_legend_when_figure_has_legend():
327+
"""Traces without labels must have showlegend=False when a figure has a legend."""
328+
fig, ax = plt.subplots()
329+
ax.plot([0, 1], [0, 1], label="Labeled line")
330+
ax.plot([0, 1], [1, 0]) # Unlabeled line
331+
ax.legend()
332+
333+
plotly_fig = tls.mpl_to_plotly(fig)
334+
335+
assert plotly_fig.layout.showlegend == True
336+
assert len(plotly_fig.data) == 2
337+
assert plotly_fig.data[0].name == "Labeled line"
338+
assert plotly_fig.data[0].showlegend is not False
339+
assert plotly_fig.data[1].name is None
340+
assert plotly_fig.data[1].showlegend is False
341+
342+
326343
def test_custom_date_xtickvals_are_converted():
327344
"""Custom tick values on a date axis must be converted to date strings,
328345
not left as raw matplotlib date numbers or datetime objects."""

0 commit comments

Comments
 (0)