I found an answer that is embedded below (I hope). It is not the most pleasing solution but it works. Working directly with screen coordinates, event.x; NOT event.xdata; the magic for mpl_connect with twinx is inv = ax1.transData.inverted() x, y = inv.transform([(event.x, event.y)]).ravel()
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
import numpy as np
import sys
coord=[]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot([0, 1, 2, 3], [1, 2, 3, 4], 'b-')
ax2.plot([0, 1, 2, 3], [40, 30, 20, 10], 'r-')
def ontwinxclick(event):
global ix
ix = event.xdata
global coord
annot = ax1.annotate("", xy=(0,0), xytext=(-40,-40),textcoords="offset points",
bbox=dict(boxstyle='round4', fc='linen',ec='k',lw=1,alpha=.936,zorder=np.inf),
arrowprops=dict(arrowstyle='-|>',zorder=np.inf),zorder=np.inf,
size=12, color='orangered',style='italic',weight='bold')
annot2 = ax2.annotate("", xy=(0,0), xytext=(-40,-40),textcoords="offset points",
bbox=dict(boxstyle='round4', fc='linen',ec='k',lw=1,alpha=.936,zorder=np.inf),
arrowprops=dict(arrowstyle='-|>',zorder=np.inf),zorder=np.inf,
size=12, color='navy',style='italic',weight='bold')
annot.set_visible(False)
annot2.set_visible(False)
import math
for i, ax in enumerate([ax1, ax2]):
if ax == event.inaxes:
print ("Click is in axes: ax{}".format(i+1))
if event.button == 3:
if ax2 == event.inaxes:
print(f'Button: {event.button}, xdata: {event.xdata}, ydata: {event.ydata}')
x=event.xdata;y=event.ydata
annot2.xy = (x,y)
text="x2={:,.2f}".format(x)
text=text+"\ny2={:,.2f}".format(y)
annot2.set_text(text)
annot2.set_visible(True)
fig.canvas.draw()
else:
print(f'Button: {event.button}, xdata: {event.xdata}, ydata: {event.ydata}')
inv = ax1.transData.inverted()
x, y = inv.transform([(event.x, event.y)]).ravel()
print(f'Screen: {event.button}, x: {event.x}, y: {event.y}')
print(f'Data: {event.button}, x: {x}, y: {y}')
annot.xy = (x,y)
text="x={:,.2f}".format(x)
text=text+"\ny={:,.2f}".format(y)
annot.set_text(text)
annot.set_visible(True)
fig.canvas.draw()
coord.append((x,y))
#pdir(event.inaxes)
#ax1.set_zorder(0.1)
cursor = Cursor(ax1, color='darkviolet', linewidth=1.2,horizOn=True, \
vertOn=True, useblit=True)
fig.canvas.mpl_connect('button_press_event', ontwinxclick)
plt.show()
The result is enter image description hereenter image description here