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

Skip to content

Commit 0f7821e

Browse files
committed
Display cursor coordinates for all axes twinned with the current one.
1 parent 46e66a7 commit 0f7821e

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
@@ -3912,10 +3912,29 @@ def format_ydata(self, y):
39123912

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

39203939
def minorticks_on(self):
39213940
"""

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)