Skip to content

Commit ada7af0

Browse files
Name stairs traces from their matplotlib labels
1 parent 6c0de2c commit ada7af0

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎plotly/matplotlylib/renderer.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -803,11 +803,19 @@ def _draw_step_path(self, props):
803803
if len(x) < 2:
804804
self.msg += " Step path has fewer than 2 points, not drawing\n"
805805
return
806+
label = props["mplobj"].get_label()
807+
if not label or (isinstance(label, str) and label.startswith("_")):
808+
label = None
809+
showlegend = False
810+
else:
811+
showlegend = None
806812
self.plotly_fig.add_trace(
807813
go.Scatter(
808814
x=x,
809815
y=y,
810816
mode="lines",
817+
name=label,
818+
showlegend=showlegend,
811819
line=go.scatter.Line(
812820
color=_export_color(style["edgecolor"], style["alpha"]),
813821
width=style["edgewidth"],

‎plotly/matplotlylib/tests/test_renderer.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,34 @@ def test_stairs_converts_to_step_line():
553553
assert tuple(trace.y) == (0.0, 0.0, 1.0, 1.0, 0.0, 0.0)
554554

555555

556+
def test_stairs_label_used_in_legend():
557+
"""A labeled stairs patch must become a named legend entry."""
558+
fig, ax = plt.subplots()
559+
ax.stairs([0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0], label="my stairs")
560+
ax.legend()
561+
562+
plotly_fig = tls.mpl_to_plotly(fig)
563+
564+
assert plotly_fig.layout.showlegend is True
565+
assert plotly_fig.data[0].name == "my stairs"
566+
assert plotly_fig.data[0].showlegend is not False
567+
568+
569+
def test_stairs_without_label_hidden_from_legend():
570+
"""An unlabeled stairs patch must not appear in the plotly legend."""
571+
fig, ax = plt.subplots()
572+
ax.stairs([0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0])
573+
ax.plot([0, 1], [2, 2], label="Labeled line")
574+
ax.legend()
575+
576+
plotly_fig = tls.mpl_to_plotly(fig)
577+
578+
assert plotly_fig.layout.showlegend is True
579+
stairs = [trace for trace in plotly_fig.data if trace.name is None]
580+
assert len(stairs) == 1
581+
assert stairs[0].showlegend is False
582+
583+
556584
def test_custom_background_colors_are_preserved():
557585
fig, ax = plt.subplots()
558586
fig.patch.set_facecolor("lightyellow")

0 commit comments

Comments
 (0)