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

Skip to content

Commit 1e3f756

Browse files
committed
Display cursor coordinates for all axes twinned with the current one.
1 parent e3a2d9e commit 1e3f756

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3910,10 +3910,32 @@ def format_ydata(self, y):
39103910

39113911
def format_coord(self, x, y):
39123912
"""Return a format string formatting the *x*, *y* coordinates."""
3913+
twins = self._twinned_axes.get_siblings(self)
3914+
if len(twins) == 1:
3915+
return "x={} y={}".format(
3916+
"???" if x is None else self.format_xdata(x),
3917+
"???" if y is None else self.format_ydata(y))
3918+
x_twins = []
3919+
y_twins = []
3920+
# Retrieve twins in the order of self.figure.axes to sort tied zorders (which is
3921+
# the common case) by the order in which they are added to the figure.
3922+
for ax in self.figure.axes:
3923+
if ax in twins:
3924+
if ax is self or ax._sharex is self or self._sharex is ax:
3925+
x_twins.append(ax)
3926+
if ax is self or ax._sharey is self or self._sharey is ax:
3927+
y_twins.append(ax)
3928+
get_zorder = attrgetter("zorder")
3929+
x_twins.sort(key=get_zorder)
3930+
y_twins.sort(key=get_zorder)
3931+
screen_xy = self.transData.transform((x, y))
39133932
return "x={} y={}".format(
3914-
"???" if x is None else self.format_xdata(x),
3915-
"???" if y is None else self.format_ydata(y),
3916-
)
3933+
" | ".join(
3934+
ax.format_xdata(ax.transData.inverted().transform(screen_xy)[0])
3935+
for ax in y_twins),
3936+
" | ".join(
3937+
ax.format_xdata(ax.transData.inverted().transform(screen_xy)[1])
3938+
for ax in x_twins))
39173939

39183940
def minorticks_on(self):
39193941
"""

lib/matplotlib/tests/test_backend_bases.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,16 @@ def test_location_event_position(x, y):
130130
assert re.match("x=foo +y=foo", ax.format_coord(x, y))
131131

132132

133+
def test_location_event_position_twin():
134+
fig, ax = plt.subplots()
135+
ax.set(xlim=(0, 10), ylim=(0, 20))
136+
assert ax.format_coord(5., 5.) == "x=5.00 y=5.00"
137+
ax.twinx().set(ylim=(0, 40))
138+
assert ax.format_coord(5., 5.) == "x=5.00 y=5.00 | 10.00"
139+
ax.twiny().set(xlim=(0, 5))
140+
assert ax.format_coord(5., 5.) == "x=5.00 | 2.50 y=5.00 | 10.00"
141+
142+
133143
def test_pick():
134144
fig = plt.figure()
135145
fig.text(.5, .5, "hello", ha="center", va="center", picker=True)

0 commit comments

Comments
 (0)