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

Skip to content

Commit d157587

Browse files
committed
FIX: Guard against already removed labels in ContourSet.remove()
1 parent ee63e75 commit d157587

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

lib/matplotlib/contour.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -513,9 +513,12 @@ def labels(self, inline, inline_spacing):
513513
self._paths[icon] = Path.make_compound_path(*additions)
514514

515515
def remove(self):
516+
axes = self.axes
516517
super().remove()
517-
for text in self.labelTexts:
518-
text.remove()
518+
for text in list(self.labelTexts):
519+
if axes is not None and text in axes.texts:
520+
text.remove()
521+
self.labelTexts.clear()
519522

520523

521524
def _find_closest_point_on_path(xys, p):

lib/matplotlib/tests/test_contour.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -876,3 +876,18 @@ def test_contour_aliases(fig_test, fig_ref):
876876
def test_contour_singular_color():
877877
with pytest.raises(TypeError):
878878
plt.figure().add_subplot().contour([[0, 1], [2, 3]], color="r")
879+
880+
def test_contour_remove_after_label_removed():
881+
# Test that CS.remove() works even if labels were manually removed first
882+
# Regression test for https://github.com/matplotlib/matplotlib/issues/31404
883+
fig, ax = plt.subplots()
884+
x = np.linspace(-3.0, 3.0, 20)
885+
y = np.linspace(-2.0, 2.0, 20)
886+
X, Y = np.meshgrid(x, y)
887+
Z = np.exp(-X**2 - Y**2)
888+
CS = ax.contour(X, Y, Z)
889+
labels = ax.clabel(CS, colors='k')
890+
for label in labels:
891+
label.remove()
892+
ax.clabel(CS, colors='r')
893+
CS.remove() # Should not raise ValueError

0 commit comments

Comments
 (0)