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

Skip to content

Commit 09bc4f0

Browse files
committed
Fix format_cursor_data with nans.
Without this fix, hovering the mouse over a nan pixel in an imshow() would result in `Warning: converting a masked element to nan.` and then `ValueError: cannot convert float NaN to integer`. Fix that. The format_cursor_data test doesn't explicitly check the return value of get_cursor_data anymore because np.ma.masked is returned for nan inputs (this is expected from the general approach for handling invalid data); checking that format_cursor_data gives the right string is sufficient.
1 parent b9193ba commit 09bc4f0

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

lib/matplotlib/artist.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1274,11 +1274,18 @@ def format_cursor_data(self, data):
12741274
# Artist.format_cursor_data would always have precedence over
12751275
# ScalarMappable.format_cursor_data.
12761276
n = self.cmap.N
1277-
# Midpoints of neighboring color intervals.
1278-
neighbors = self.norm.inverse(
1279-
(int(self.norm(data) * n) + np.array([0, 1])) / n)
1280-
delta = abs(neighbors - data).max()
1281-
return "[{:-#.{}g}]".format(data, cbook._g_sig_digits(data, delta))
1277+
if np.ma.getmask(data):
1278+
return "[]"
1279+
normed = self.norm(data)
1280+
if np.isfinite(normed):
1281+
# Midpoints of neighboring color intervals.
1282+
neighbors = self.norm.inverse(
1283+
(int(self.norm(data) * n) + np.array([0, 1])) / n)
1284+
delta = abs(neighbors - data).max()
1285+
g_sig_digits = cbook._g_sig_digits(data, delta)
1286+
else:
1287+
g_sig_digits = 3 # Consistent with default below.
1288+
return "[{:-#.{}g}]".format(data, g_sig_digits)
12821289
else:
12831290
try:
12841291
data[0]

lib/matplotlib/tests/test_image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ def test_cursor_data():
340340
"data, text", [
341341
([[10001, 10000]], "[10001.000]"),
342342
([[.123, .987]], "[0.123]"),
343+
([[np.nan, 1, 2]], "[]"),
343344
])
344345
def test_format_cursor_data(data, text):
345346
from matplotlib.backend_bases import MouseEvent
@@ -349,7 +350,6 @@ def test_format_cursor_data(data, text):
349350

350351
xdisp, ydisp = ax.transData.transform([0, 0])
351352
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
352-
assert im.get_cursor_data(event) == data[0][0]
353353
assert im.format_cursor_data(im.get_cursor_data(event)) == text
354354

355355

0 commit comments

Comments
 (0)