Skip to content
14 changes: 13 additions & 1 deletion lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""
Classes to support contour plotting and labelling for the Axes class.
"""
Expand Down Expand Up @@ -143,6 +143,11 @@
-------
labels
A list of `.Text` instances for the labels.

Note: The returned Text instances should not be individually
removed or have their geometry modified, e.g. by changing text or font size.
If you need such a modification, remove the entire
`.ContourSet` and recreate it.
"""

if self.filled:
Expand Down Expand Up @@ -515,7 +520,14 @@
def remove(self):
super().remove()
for text in self.labelTexts:
text.remove()
try:
text.remove()
except ValueError:
_api.warn_external(
"Some labels were manually removed from the ContourSet. "
"To remove labels cleanly, remove the entire ContourSet "
"and recreate it.")
self.labelTexts.clear()


def _find_closest_point_on_path(xys, p):
Expand Down
9 changes: 9 additions & 0 deletions lib/matplotlib/tests/test_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,15 @@ def test_contour_remove():
assert ax.get_children() == orig_children


def test_contour_remove_with_labels():
ax = plt.figure().add_subplot()
cs = ax.contour(np.arange(16).reshape((4, 4)))
labels = cs.clabel()
labels[0].remove()
with pytest.warns(UserWarning, match="Some labels were manually removed"):
cs.remove()


def test_contour_no_args():
fig, ax = plt.subplots()
data = [[0, 1], [1, 0]]
Expand Down
Loading