【问题标题】:Determine button clicked subplot in matplotlib在matplotlib中确定按钮单击的子图
【发布时间】:2014-07-30 22:11:12
【问题描述】:

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

例如

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-06
        • 1970-01-01
        • 2021-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        相关资源
        最近更新 更多