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

Skip to content

Commit 84a5601

Browse files
committed
Display cursor coordinates for all axes twinned with the current one.
1 parent 7baa2b8 commit 84a5601

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
@@ -3906,10 +3906,32 @@ def format_ydata(self, y):
39063906

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

39143936
def minorticks_on(self):
39153937
"""

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)