确定在 matplotlib 中单击按钮的子图

mem*_*ecs 5 python matplotlib

给定一个带有多个图的图形,有没有办法确定用鼠标按钮单击了哪个图?

例如

fig = plt.figure()

ax  = fig.add_subplot(121)
ax.imshow(imsp0)

ax = fig.add_subplot(122)
ax.imshow(imsp1)

fig.canvas.mpl_connect("button_press_event",onclick_select)

def onclick_select(event):
  ... do something depending on the clicked subplot
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

如果您保留两个轴的句柄,则可以只查询发生单击的轴;例如if event.inaxes == ax:

import matplotlib.pyplot as plt
import numpy as np

imsp0 = np.random.rand(10,10)
imsp1 = np.random.rand(10,10)

fig = plt.figure()

ax  = fig.add_subplot(121)
ax.imshow(imsp0)

ax2 = fig.add_subplot(122)
ax2.imshow(imsp1)

def onclick_select(event):
    if event.inaxes == ax:
        print ("event in ax")
    elif event.inaxes == ax2:
        print ("event in ax2")

fig.canvas.mpl_connect("button_press_event",onclick_select)

plt.show()
Run Code Online (Sandbox Code Playgroud)


DrV*_*DrV 2

至少可以通过应用以下步骤来实现:

  • onclick 事件具有属性xy携带图形角点的像素坐标

  • 这些坐标可以通过使用转换为图形坐标fig.transFigure.inverted().transform((x,y))

  • 您可以通过以下方式获取每个子图的边界框bb=ax.get_position()

  • 迭代图像的所有子图(轴)

  • 您可以通过以下方式测试单击是否在此边界框的区域内bb.contains(fx,fy),其中fxfy是按钮单击坐标转换为图像位置

有关 onclick 事件的更多信息:http://matplotlib.org/users/event_handling.html 有关坐标转换的更多信息:http://matplotlib.org/users/transforms_tutorial.html