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

Skip to content

Commit 98023a2

Browse files
authored
Merge pull request #18737 from alexschlueter/fix_transformed_img_cursor
Fix data cursor for images with additional transform
2 parents 777cba6 + 7a91945 commit 98023a2

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

lib/matplotlib/image.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -660,7 +660,8 @@ def contains(self, mouseevent):
660660
# collection on nonlinear transformed coordinates.
661661
# TODO: consider returning image coordinates (shouldn't
662662
# be too difficult given that the image is rectilinear
663-
x, y = mouseevent.xdata, mouseevent.ydata
663+
trans = self.get_transform().inverted()
664+
x, y = trans.transform([mouseevent.x, mouseevent.y])
664665
xmin, xmax, ymin, ymax = self.get_extent()
665666
if xmin > xmax:
666667
xmin, xmax = xmax, xmin
@@ -982,13 +983,14 @@ def get_cursor_data(self, event):
982983
if self.origin == 'upper':
983984
ymin, ymax = ymax, ymin
984985
arr = self.get_array()
985-
data_extent = Bbox([[ymin, xmin], [ymax, xmax]])
986-
array_extent = Bbox([[0, 0], arr.shape[:2]])
987-
trans = BboxTransform(boxin=data_extent, boxout=array_extent)
988-
point = trans.transform([event.ydata, event.xdata])
986+
data_extent = Bbox([[xmin, ymin], [xmax, ymax]])
987+
array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]])
988+
trans = self.get_transform().inverted()
989+
trans += BboxTransform(boxin=data_extent, boxout=array_extent)
990+
point = trans.transform([event.x, event.y])
989991
if any(np.isnan(point)):
990992
return None
991-
i, j = point.astype(int)
993+
j, i = point.astype(int)
992994
# Clip the coordinates at array bounds
993995
if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
994996
return None

lib/matplotlib/tests/test_image.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,15 @@ def test_cursor_data():
325325
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
326326
assert im.get_cursor_data(event) is None
327327

328+
# Now try with additional transform applied to the image artist
329+
trans = Affine2D().scale(2).rotate(0.5)
330+
im = ax.imshow(np.arange(100).reshape(10, 10),
331+
transform=trans + ax.transData)
332+
x, y = 3, 10
333+
xdisp, ydisp = ax.transData.transform([x, y])
334+
event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
335+
assert im.get_cursor_data(event) == 44
336+
328337

329338
@pytest.mark.parametrize(
330339
"data, text_without_colorbar, text_with_colorbar", [

0 commit comments

Comments
 (0)