8000 Merge pull request #20859 from tomneep/subfigure-legend · matplotlib/matplotlib@98306f9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 98306f9

Browse files
authored
Merge pull request #20859 from tomneep/subfigure-legend
2 parents a4e81e7 + 7da7795 commit 98306f9

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

lib/matplotlib/legend.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def __init__(
360360
"""
361361
# local import only to avoid circularity
362362
from matplotlib.axes import Axes
363-
from matplotlib.figure import Figure
363+
from matplotlib.figure import FigureBase
364364

365365
super().__init__()
366366

@@ -434,11 +434,13 @@ def __init__(
434434
self.isaxes = True
435435
self.axes = parent
436436
self.set_figure(parent.figure)
437-
elif isinstance(parent, Figure):
437+
elif isinstance(parent, FigureBase):
438438
self.isaxes = False
439439
self.set_figure(parent)
440440
else:
441-
raise TypeError("Legend needs either Axes or Figure as parent")
441+
raise TypeError(
442+
"Legend needs either Axes or FigureBase as parent"
443+
)
442444
self.parent = parent
443445

444446
self._loc_used_default = loc is None

lib/matplotlib/tests/test_legend.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -871,3 +871,12 @@ def test_handlerline2d():
871871
handles = [mlines.Line2D([0], [0], marker="v")]
872872
leg = ax.legend(handles, ["Aardvark"], numpoints=1)
873873
assert handles[0].get_marker() == leg.legendHandles[0].get_marker()
874+
875+
876+
def test_subfigure_legend():
877+
# Test that legend can be added to subfigure (#20723)
878+
subfig = plt.figure().subfigures()
879+
ax = subfig.subplots()
880+
ax.plot([0, 1], [0, 1], label="line")
881+
leg = subfig.legend()
882+
assert leg.figure is subfig

0 commit comments

Comments
 (0)
0