You can track both axis coordinates with a single cursor (or event handler) as follows:
import numpy as np import matplotlib.pyplot as plt import logging logger = logging.getLogger(__name__) class Cursor(object): def __init__(self): plt.connect('motion_notify_event', self) def __call__(self, event): if event.inaxes is None: return x, y1 = ax1.transData.inverted().transform((event.x,event.y)) x, y2 = ax2.transData.inverted().transform((event.x,event.y)) logger.debug('(x,y1,y2)=({x:0.2f}, {y1:0.2f}, {y2:0.2f})'.format(x=x,y1=y1,y2=y2)) logging.basicConfig(level=logging.DEBUG, format='%(message)s',) fig, ax1 = plt.subplots() x = np.linspace(1000, 2000, 500) y = 100*np.sin(20*np.pi*(x-1500)/2000.0) fern = Cursor() ax1.plot(x,y) ax2 = ax1.twinx() z = x/200.0 ax2.plot(x,z) plt.show()
(I got "too many indexes" when I used ax2.semilogy(x,z) as an OP, but could not handle this problem.)
The code ax1.transData.inverted().transform((event.x,event.y)) performs the conversion from display to the data coordinates on the specified axis and can be used with any axis as desired.
source share