cursor tracking using matplotlib and twinx

后端 未结 2 1731
清歌不尽
清歌不尽 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:39

    Due to the way that the call backs work, the event always returns in the top axes. You just need a bit of logic to check which if the event happens in the axes we want:

    class Cursor(object):
        def __init__(self, ax, x, y, name):
            self.ax = ax
            self.name = name
            plt.connect('motion_notify_event', self)
    
        def __call__(self, event):
            if event.inaxes is None:
                return
            ax = self.ax
            if ax != event.inaxes:
                inv = ax.transData.inverted()
                x, y = inv.transform(np.array((event.x, event.y)).reshape(1, 2)).ravel()
            elif ax == event.inaxes:
                x, y = event.xdata, event.ydata
            else:
                return
            logger.debug('{n}: ({x:0.2f}, {y:0.2f})'.format(n=self.name,x=x,y=y))
    

    This might be a subtle bug down in the transform stack (or this is the correct usage and it was by luck it worked with tuples before), but at any rate, this will make it work. The issue is that the code at line 1996 in transform.py expects to get a 2D ndarray back, but the identity transform just returns the tuple that get handed into it, which is what generates the errors.

提交回复
热议问题