Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit d9bb0a2

Browse filesBrowse files
committed
Implement get_cursor_data for QuadMesh.
The motivation is actually to provide get_cursor_data for hist2d, which uses a QuadMesh to draw itself (see the test). As it turns out, Collection.contains already contains the relevant code to find which path contains the mouse event, so just reuse that.
1 parent 5958725 commit d9bb0a2
Copy full SHA for d9bb0a2

File tree

4 files changed

+52
-21
lines changed
Filter options

4 files changed

+52
-21
lines changed

‎lib/matplotlib/artist.py

Copy file name to clipboardExpand all lines: lib/matplotlib/artist.py
+22-8Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,19 +1251,33 @@ def format_cursor_data(self, data):
12511251
method yourself.
12521252
12531253
The default implementation converts ints and floats and arrays of ints
1254-
and floats into a comma-separated string enclosed in square brackets.
1254+
and floats into a comma-separated string enclosed in square brackets,
1255+
unless the artist has an associated colorbar, in which case scalar
1256+
values are formatted using the colorbar's formatter.
12551257
12561258
See Also
12571259
--------
12581260
get_cursor_data
12591261
"""
1260-
try:
1261-
data[0]
1262-
except (TypeError, IndexError):
1263-
data = [data]
1264-
data_str = ', '.join('{:0.3g}'.format(item) for item in data
1265-
if isinstance(item, Number))
1266-
return "[" + data_str + "]"
1262+
if np.ndim(data) == 0 and getattr(self, "colorbar", None):
1263+
# This block logically belongs to ScalarMappable, but can't be
1264+
# implemented in it because most ScalarMappable subclasses inherit
1265+
# from Artist first and from ScalarMappable second, so
1266+
# Artist.format_cursor_data would always have precedence over
1267+
# ScalarMappable.format_cursor_data.
1268+
return (
1269+
"["
1270+
+ cbook.strip_math(
1271+
self.colorbar.formatter.format_data_short(data)).strip()
1272+
+ "]")
1273+
else:
1274+
try:
1275+
data[0]
1276+
except (TypeError, IndexError):
1277+
data = [data]
1278+
data_str = ', '.join('{:0.3g}'.format(item) for item in data
1279+
if isinstance(item, Number))
1280+
return "[" + data_str + "]"
12671281

12681282
@property
12691283
def mouseover(self):

‎lib/matplotlib/collections.py

Copy file name to clipboardExpand all lines: lib/matplotlib/collections.py
+16-3Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1930,7 +1930,7 @@ def draw(self, renderer):
19301930

19311931

19321932
class QuadMesh(Collection):
1933-
"""
1933+
r"""
19341934
Class for the efficient drawing of a quadrilateral mesh.
19351935
19361936
A quadrilateral mesh is a grid of M by N adjacent qudrilaterals that are
@@ -1957,6 +1957,10 @@ class QuadMesh(Collection):
19571957
19581958
Notes
19591959
-----
1960+
Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
1961+
i.e. `~.Artist.contains` checks whether the test point is within any of the
1962+
mesh quadrilaterals.
1963+
19601964
There exists a deprecated API version ``QuadMesh(M, N, coords)``, where
19611965
the dimensions are given explicitly and ``coords`` is a (M*N, 2)
19621966
array-like. This has been deprecated in Matplotlib 3.5. The following
@@ -1984,8 +1988,8 @@ class QuadMesh(Collection):
19841988
For example, the first entry in *coordinates* is the coordinates of the
19851989
vertex at mesh coordinates (0, 0), then the one at (0, 1), then at (0, 2)
19861990
.. (0, meshWidth), (1, 0), (1, 1), and so on.
1987-
19881991
"""
1992+
19891993
def __init__(self, *args, **kwargs):
19901994
# signature deprecation since="3.5": Change to new signature after the
19911995
# deprecation has expired. Also remove setting __init__.__signature__,
@@ -2017,6 +2021,7 @@ def __init__(self, *args, **kwargs):
20172021
"coordinates must be 2D; all parameters except "
20182022
"coordinates will be keyword-only.")
20192023
coords = np.asarray(coords, np.float64).reshape((h + 1, w + 1, 2))
2024+
kwargs.setdefault("pickradius", 0)
20202025
# end of signature deprecation code
20212026

20222027
super().__init__(**kwargs)
@@ -2031,7 +2036,7 @@ def __init__(self, *args, **kwargs):
20312036
# Only needed during signature deprecation
20322037
__init__.__signature__ = inspect.signature(
20332038
lambda self, coordinates, *,
2034-
antialiased=True, shading='flat', **kwargs: None)
2039+
antialiased=True, shading='flat', pickradius=0, **kwargs: None)
20352040

20362041
def get_paths(self):
20372042
if self._paths is None:
@@ -2162,3 +2167,11 @@ def draw(self, renderer):
21622167
gc.restore()
21632168
renderer.close_group(self.__class__.__name__)
21642169
self.stale = False
2170+
2171+
def get_cursor_data(self, event):
2172+
contained, info = self.contains(event)
2173+
if len(info["ind"]) == 1:
2174+
ind, = info["ind"]
2175+
return self.get_array()[ind]
2176+
else:
2177+
return None

‎lib/matplotlib/image.py

Copy file name to clipboardExpand all lines: lib/matplotlib/image.py
-10Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -995,16 +995,6 @@ def get_cursor_data(self, event):
995995
else:
996996
return arr[i, j]
997997

998-
def format_cursor_data(self, data):
999-
if np.ndim(data) == 0 and self.colorbar:
1000-
return (
1001-
"["
1002-
+ cbook.strip_math(
1003-
self.colorbar.formatter.format_data_short(data)).strip()
1004-
+ "]")
1005-
else:
1006-
return super().format_cursor_data(data)
1007-
1008998

1009999
class NonUniformImage(AxesImage):
10101000
mouseover = False # This class still needs its own get_cursor_data impl.

‎lib/matplotlib/tests/test_collections.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_collections.py
+14Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import matplotlib as mpl
99
import matplotlib.pyplot as plt
10+
from matplotlib.backend_bases import MouseEvent
1011
import matplotlib.collections as mcollections
1112
import matplotlib.colors as mcolors
1213
import matplotlib.transforms as mtransforms
@@ -972,3 +973,16 @@ def test_array_wrong_dimensions():
972973
pc = plt.pcolormesh(z)
973974
pc.set_array(z) # 2D is OK for Quadmesh
974975
pc.update_scalarmappable()
976+
977+
978+
def test_quadmesh_cursor_data():
979+
fig, ax = plt.subplots()
980+
*_, qm = ax.hist2d(
981+
np.arange(11)**2, 100 + np.arange(11)**2) # width-10 bins
982+
x, y = ax.transData.transform([1, 101])
983+
event = MouseEvent('motion_notify_event', fig.canvas, x, y)
984+
assert qm.get_cursor_data(event) == 4 # (0**2, 1**2, 2**2, 3**2)
985+
for out_xydata in []:
986+
x, y = ax.transData.transform([-1, 101])
987+
event = MouseEvent('motion_notify_event', fig.canvas, x, y)
988+
assert qm.get_cursor_data(event) is None

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.