获取单击点相对于子图的索引



我在matplotlib有一个图,有 2 个子图:

plt.subplot(211), plt.imshow(img1)
plt.subplot(212, plt.imshow(img2)

我设置了一个单击处理程序来处理鼠标单击事件:

fig = plt.figure()
def onclick(event):
    print plot.x, plot.y
cid = fig.canvas.mpl_connect('button_press_event', onclick)

问题是event.x返回点击点相对于整个图的索引,我想要的是相对于第二个子图的索引。如何获取相对于子图的索引?

你需要做两件事才能正常工作。首先,回调函数必须检查单击是否在感兴趣的轴内。其次,鼠标事件位置以显示坐标给出,必须将其转换为轴坐标。第一个要求可以通过使用 Axes.in_axes() 来完成。第二个可以通过Axes.transAxes变换来实现。(此转换从轴转换为显示坐标,因此必须反转才能从显示坐标转换为轴坐标。

一个小例子可能是:

import matplotlib.pyplot as plt
import functools
def handler(fig, ax, event):
    # Verify click is within the axes of interest
    if ax.in_axes(event):
        # Transform the event from display to axes coordinates
        ax_pos = ax.transAxes.inverted().transform((event.x, event.y))
        print(ax_pos)
if __name__ == '__main__':
    fig, axes = plt.subplots(2, 1)
    # Handle click events only in the bottom of the two axes
    handler_wrapper = functools.partial(handler, fig, axes[1])
    fig.canvas.mpl_connect('button_press_event', handler_wrapper)
    plt.show()

最新更新