确定图表中 matplotlib 中单击的按钮位置

2024-09-27 09:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个有多个绘图的图形,有没有一种方法可以确定哪些是用鼠标键单击的?在

例如

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

Tags: 方法eventadd图形绘图figpltax
2条回答

如果您保留了两个轴的句柄,您可以只查询单击发生的轴;例如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()

至少可以采用以下步骤:

  • onclick事件具有xy属性,它们携带图形角落的像素坐标

  • 可以使用fig.transFigure.inverted().transform((x,y))

    将这些坐标转换为图形坐标
  • 您可以通过bb=ax.get_position()

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

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

有关onclick事件的详细信息:http://matplotlib.org/users/event_handling.html 有关坐标变换的详细信息:http://matplotlib.org/users/transforms_tutorial.html

相关问题 更多 >

    热门问题