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

Skip to content

Commit f50c05e

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

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3969,10 +3969,29 @@ def format_ydata(self, y):
39693969

39703970
def format_coord(self, x, y):
39713971
"""Return a format string formatting the *x*, *y* coordinates."""
3972+
twins = self._twinned_axes.get_siblings(self)
3973+
if len(twins) == 1:
3974+
return "x={} y={}".format(
3975+
"???" if x is None else self.format_xdata(x),
3976+
"???" if y is None else self.format_ydata(y))
3977+
x_twins = []
3978+
y_twins = []
3979+
# Retrieve twins in the order of self.figure.axes to sort tied zorders (which is
3980+
# the common case) by the order in which they are added to the figure.
3981+
for ax in self.figure.axes:
3982+
if ax in twins:
3983+
if ax is self or ax._sharex is self or self._sharex is ax:
3984+
x_twins.append(ax)
3985+
if ax is self or ax._sharey is self or self._sharey is ax:
3986+
y_twins.append(ax)
3987+
screen_xy = self.transData.transform((x, y))
39723988
return "x={} y={}".format(
3973-
"???" if x is None else self.format_xdata(x),
3974-
"???" if y is None else self.format_ydata(y),
3975-
)
3989+
" | ".join(
3990+
ax.format_xdata(ax.transData.inverted().transform(screen_xy)[0])
3991+
for ax in sorted(y_twins, key=attrgetter("zorder"))),
3992+
" | ".join(
3993+
ax.format_xdata(ax.transData.inverted().transform(screen_xy)[1])
3994+
for ax in sorted(x_twins, key=attrgetter("zorder"))))
39763995

39773996
def minorticks_on(self):
39783997
"""

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)