Skip to content

Commit

Permalink
Fixed bug in find_nearest_contour; Added test
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew-fennell committed Apr 11, 2022
1 parent 6c3412b commit 4a47543
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/matplotlib/contour.py
Expand Up @@ -1334,6 +1334,8 @@ def find_nearest_contour(self, x, y, indices=None, pixel=True):
"""
Find the point in the contour plot that is closest to ``(x, y)``.
This method does not support filled contours.
Parameters
----------
x, y : float
Expand Down Expand Up @@ -1370,8 +1372,11 @@ def find_nearest_contour(self, x, y, indices=None, pixel=True):
# sufficiently well that the time is not noticeable.
# Nonetheless, improvements could probably be made.

if self.filled:
raise ValueError("Method does not support filled contours.")

if indices is None:
indices = range(len(self.levels))
indices = range(len(self.collections))

d2min = np.inf
conmin = None
Expand Down
42 changes: 42 additions & 0 deletions lib/matplotlib/tests/test_contour.py
Expand Up @@ -470,6 +470,48 @@ def test_contour_line_start_on_corner_edge():
cbar.add_lines(lines)


def test_find_nearest_contour():
xy = np.indices((15, 15))
img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))
cs = plt.contour(img, 10)

nearest_contour = cs.find_nearest_contour(1, 1, pixel=False)
expected_nearest = (1, 0, 33, 1.965966, 1.965966, 1.866183)
assert_array_almost_equal(nearest_contour, expected_nearest)

nearest_contour = cs.find_nearest_contour(8, 1, pixel=False)
expected_nearest = (1, 0, 5, 7.550173, 1.587542, 0.547550)
assert_array_almost_equal(nearest_contour, expected_nearest)

nearest_contour = cs.find_nearest_contour(2, 5, pixel=False)
expected_nearest = (3, 0, 21, 1.884384, 5.023335, 0.013911)
assert_array_almost_equal(nearest_contour, expected_nearest)

nearest_contour = cs.find_nearest_contour(2, 5,
indices=(5, 7),
pixel=False)
expected_nearest = (5, 0, 16, 2.628202, 5.0, 0.394638)
assert_array_almost_equal(nearest_contour, expected_nearest)


def test_find_nearest_contour_no_filled():
xy = np.indices((15, 15))
img = np.exp(-np.pi * (np.sum((xy - 5)**2, 0)/5.**2))
cs = plt.contourf(img, 10)

with pytest.raises(ValueError,
match="Method does not support filled contours."):
cs.find_nearest_contour(1, 1, pixel=False)

with pytest.raises(ValueError,
match="Method does not support filled contours."):
cs.find_nearest_contour(1, 10, indices=(5, 7), pixel=False)

with pytest.raises(ValueError,
match="Method does not support filled contours."):
cs.find_nearest_contour(2, 5, indices=(2, 7), pixel=True)


@mpl.style.context("default")
def test_contour_autolabel_beyond_powerlimits():
ax = plt.figure().add_subplot()
Expand Down

0 comments on commit 4a47543

Please sign in to comment.