Skip to content

Commit 7388a2b

Browse files
Only show a legend when the matplotlib figure has one
1 parent d3105d4 commit 7388a2b

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

‎plotly/matplotlylib/renderer.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ def open_figure(self, fig, props):
100100
height=int(props["figheight"] * props["dpi"]),
101101
autosize=False,
102102
hovermode="closest",
103+
# plotly.js auto-names unnamed traces "trace N" and shows them
104+
# in the legend; the legend is only enabled when the mpl figure
105+
# actually has one (see open_legend)
106+
showlegend=False,
103107
)
104108
self.plotly_fig["layout"].paper_bgcolor = _export_color(props["figbg"])
105109
self.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig)
@@ -440,13 +444,14 @@ def draw_marked_line(self, **props):
440444
),
441445
)
442446
if props["coordinates"] == "data":
447+
label = props["label"]
448+
# matplotlib uses "_nolegend_" and auto-generated "_childN"
449+
# labels for artists that must not appear in a legend
450+
if isinstance(label, str) and label.startswith("_"):
451+
label = None
443452
marked_line = go.Scatter(
444453
mode=mode,
445-
name=(
446-
str(props["label"])
447-
if isinstance(props["label"], str)
448-
else props["label"]
449-
),
454+
name=label,
450455
x=[xy_pair[0] for xy_pair in props["data"]],
451456
y=[xy_pair[1] for xy_pair in props["data"]],
452457
xaxis="x{0}".format(self.axis_ct),

‎plotly/matplotlylib/tests/test_renderer.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,17 @@ def test_fixed_formatter_ticktext():
297297
assert plotly_fig.layout.xaxis.ticktext == ("Baseline", "param = 1", "param = 2")
298298

299299

300+
def test_no_legend_entries_for_internal_mpl_labels():
301+
"""mpl internal labels (_nolegend_, _childN) must not become legend entries."""
302+
fig, ax = plt.subplots()
303+
ax.plot([0, 1, 2, 3], [0, 1, 0, 1], "b", [0, 1, 2, 3], [1, 0, 1, 0], "r--")
304+
305+
plotly_fig = tls.mpl_to_plotly(fig)
306+
307+
assert plotly_fig.layout.showlegend == False
308+
assert all(t.name is None for t in plotly_fig.data)
309+
310+
300311
def test_custom_date_xtickvals_are_converted():
301312
"""Custom tick values on a date axis must be converted to date strings,
302313
not left as raw matplotlib date numbers or datetime objects."""

0 commit comments

Comments
 (0)