Skip to content

Commit b7c8966

Browse files
Show labeled spans in the legend
1 parent d823d7e commit b7c8966

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

‎plotly/matplotlylib/renderer.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,9 @@ def _draw_axes_span(self, props):
769769
fillcolor = _export_color(style["facecolor"])
770770
edgecolor = _export_color(style["edgecolor"])
771771
linewidth = style["edgewidth"] if style["edgecolor"] != "none" else 0
772+
label = props["mplobj"].get_label()
773+
if not label or (isinstance(label, str) and label.startswith("_")):
774+
label = None
772775
shape = go.layout.Shape(
773776
type="rect",
774777
x0=x0,
@@ -784,6 +787,8 @@ def _draw_axes_span(self, props):
784787
dash=mpltools.convert_dash(style["dasharray"]),
785788
),
786789
layer="below" if style.get("zorder", 1) < 2 else "above",
790+
name=label,
791+
showlegend=True if label is not None else None,
787792
)
788793
self.plotly_fig["layout"]["shapes"] += (shape,)
789794
self.msg += " Heck yeah, I drew that reference span\n"

‎plotly/matplotlylib/tests/test_renderer.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1525,3 +1525,19 @@ def test_axvspan_on_date_xaxis_converts_to_dates():
15251525
assert vspan.x1.startswith("2023-01-06")
15261526
assert hspan.xref == "x domain"
15271527
assert np.allclose([hspan.x0, hspan.x1], [0, 1])
1528+
1529+
1530+
def test_labeled_axvspan_shows_in_legend():
1531+
"""A labeled span exports its label as the shape legend entry."""
1532+
fig, ax = plt.subplots()
1533+
ax.plot([0, 10], [0, 10], label="line")
1534+
ax.axvspan(2, 4, label="span")
1535+
ax.axhspan(6, 8)
1536+
ax.legend()
1537+
1538+
plotly_fig = tls.mpl_to_plotly(fig)
1539+
1540+
labeled, unlabeled = plotly_fig.layout.shapes
1541+
assert labeled.name == "span"
1542+
assert labeled.showlegend is True
1543+
assert unlabeled.showlegend is None

0 commit comments

Comments
 (0)