cursor tracking using matplotlib and twinx

后端 未结 2 1730
清歌不尽
清歌不尽 2020-12-06 20:54

I would like to track the coordinates of the mouse with respect to data coordinates on two axes simultaneously. I can track the mouse position with respect to one a

2条回答
  •  余生分开走
    2020-12-06 21:37

    You can track both axis coordinates with one cursor (or event handler) this way:

    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 indices" when I used ax2.semilogy(x,z) like the OP, but didn't work through that problem.)

    The ax1.transData.inverted().transform((event.x,event.y)) code performs a transform from display to data coordinates on the specified axis and can be used with either axis at will.

提交回复
热议问题