Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0bcfe16

Browse files
committed
Detach legend when clearing an Axes via clear/cla
1 parent 49590bb commit 0bcfe16

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,6 +1298,9 @@ def __clear(self):
12981298
self.child_axes = []
12991299
self._current_image = None # strictly for pyplot via _sci, _gci
13001300
self._projection_init = None # strictly for pyplot.subplot
1301+
1302+
if hasattr(self, "legend_") and self.legend_ is not None:
1303+
self.legend_.axes = self.legend_.figure = None
13011304
self.legend_ = None
13021305
self.containers = []
13031306

lib/matplotlib/tests/test_axes.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8644,13 +8644,19 @@ def test_extent_units():
86448644

86458645
def test_cla_clears_children_axes_and_fig():
86468646
fig, ax = plt.subplots()
8647-
lines = ax.plot([], [], [], [])
8647+
8648+
lines = ax.plot([], [], [], [], label="line")
86488649
img = ax.imshow([[1]])
8649-
for art in lines + [img]:
8650+
legend = ax.legend()
8651+
8652+
children = [*lines, img, legend]
8653+
8654+
for art in children:
86508655
assert art.axes is ax
86518656
assert art.figure is fig
8657+
86528658
ax.clear()
8653-
for art in lines + [img]:
8659+
for art in children:
86548660
assert art.axes is None
86558661
assert art.figure is None
86568662

0 commit comments

Comments
 (0)