Skip to content
17 changes: 15 additions & 2 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ def clabel(self, levels=None, *,
-------
labels
A list of `.Text` instances for the labels.

Note: The returned .Text instances should not be individually
Comment thread
timhoffm marked this conversation as resolved.
Outdated
removed or have their geometry modified. To remove all labels,
Comment thread
timhoffm marked this conversation as resolved.
Outdated
remove the entire .ContourSet and recreate it.
Comment thread
timhoffm marked this conversation as resolved.
Outdated
"""

if self.filled:
Expand Down Expand Up @@ -514,8 +518,17 @@ def labels(self, inline, inline_spacing):

def remove(self):
super().remove()
for text in self.labelTexts:
text.remove()
for text in list(self.labelTexts):
Comment thread
timhoffm marked this conversation as resolved.
Outdated
try:
text.remove()
except ValueError:
import warnings
warnings.warn(
Comment thread
timhoffm marked this conversation as resolved.
Outdated
"Some labels were manually removed before the ContourSet. "
Comment thread
buddy0452004 marked this conversation as resolved.
Outdated
"To remove labels cleanly, remove the entire ContourSet "
"and recreate it.",
UserWarning, stacklevel=2)
self.labelTexts.clear()


def _find_closest_point_on_path(xys, p):
Expand Down
11 changes: 11 additions & 0 deletions lib/matplotlib/tests/test_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,17 @@ 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()
for label in labels:
Comment thread
timhoffm marked this conversation as resolved.
Outdated
label.remove()
cs.clabel()
Comment thread
timhoffm marked this conversation as resolved.
Outdated
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