Skip to content

Commit 831477a

Browse files
authored
Merge pull request matplotlib#31431 from buddy0452004/fix-contour-remove-crash-v2
FIX: Guard against already-removed labels in ContourSet.remove()
2 parents 4cefc05 + 5f1d6b0 commit 831477a

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

lib/matplotlib/contour.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,11 @@ def clabel(self, levels=None, *,
143143
-------
144144
labels
145145
A list of `.Text` instances for the labels.
146+
147+
Note: The returned Text instances should not be individually
148+
removed or have their geometry modified, e.g. by changing text or font size.
149+
If you need such a modification, remove the entire
150+
`.ContourSet` and recreate it.
146151
"""
147152

148153
if self.filled:
@@ -515,7 +520,14 @@ def labels(self, inline, inline_spacing):
515520
def remove(self):
516521
super().remove()
517522
for text in self.labelTexts:
518-
text.remove()
523+
try:
524+
text.remove()
525+
except ValueError:
526+
_api.warn_external(
527+
"Some labels were manually removed from the ContourSet. "
528+
"To remove labels cleanly, remove the entire ContourSet "
529+
"and recreate it.")
530+
self.labelTexts.clear()
519531

520532

521533
def _find_closest_point_on_path(xys, p):

lib/matplotlib/tests/test_contour.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,15 @@ def test_contour_remove():
803803
assert ax.get_children() == orig_children
804804

805805

806+
def test_contour_remove_with_labels():
807+
ax = plt.figure().add_subplot()
808+
cs = ax.contour(np.arange(16).reshape((4, 4)))
809+
labels = cs.clabel()
810+
labels[0].remove()
811+
with pytest.warns(UserWarning, match="Some labels were manually removed"):
812+
cs.remove()
813+
814+
806815
def test_contour_no_args():
807816
fig, ax = plt.subplots()
808817
data = [[0, 1], [1, 0]]

0 commit comments

Comments
 (0)