Skip to content

Commit e405fe0

Browse files
Only show a legend when the matplotlib figure has one
1 parent a5974ce commit e405fe0

2 files changed

Lines changed: 19 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.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig)
105109
margin = go.layout.Margin(
@@ -437,13 +441,14 @@ def draw_marked_line(self, **props):
437441
),
438442
)
439443
if props["coordinates"] == "data":
444+
label = props["label"]
445+
# matplotlib uses "_nolegend_" and auto-generated "_childN"
446+
# labels for artists that must not appear in a legend
447+
if isinstance(label, str) and label.startswith("_"):
448+
label = None
440449
marked_line = go.Scatter(
441450
mode=mode,
442-
name=(
443-
str(props["label"])
444-
if isinstance(props["label"], str)
445-
else props["label"]
446-
),
451+
name=label,
447452
x=[xy_pair[0] for xy_pair in props["data"]],
448453
y=[xy_pair[1] for xy_pair in props["data"]],
449454
xaxis="x{0}".format(self.axis_ct),

plotly/matplotlylib/tests/test_renderer.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,12 @@ def test_filled_path_collection_date_xaxis():
199199
filled = [t for t in plotly_fig.data if t.fill == "toself"]
200200
assert len(filled) >= 1
201201
assert all(isinstance(x, str) for x in filled[0].x)
202+
203+
204+
def test_no_legend_entries_for_internal_mpl_labels():
205+
"""mpl internal labels (_nolegend_, _childN) must not become legend entries."""
206+
fig, ax = plt.subplots()
207+
ax.plot([0, 1, 2, 3], [0, 1, 0, 1], "b", [0, 1, 2, 3], [1, 0, 1, 0], "r--")
208+
plotly_fig = tls.mpl_to_plotly(fig)
209+
assert plotly_fig.layout.showlegend == False
210+
assert all(t.name is None for t in plotly_fig.data)

0 commit comments

Comments
 (0)