代码之家  ›  专栏  ›  技术社区  ›  Gabriel

区分button\u press\u事件与matplotlib中的拖动和缩放单击

  •  5
  • Gabriel  · 技术社区  · 8 年前

    我有一个简单的代码,它显示了两个子地块,并允许用户在录制 x,y 这些点击的坐标。

    问题是,选择要缩放的区域并拖动子地块的单击也被标识为左键单击。

    有没有办法区分和过滤这些左键点击?

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def onclick(event, ax):
        # Only clicks inside this axis are valid.
        if event.inaxes == ax:
            if event.button == 1:
                print(event.xdata, event.ydata)
                # Draw the click just made
                ax.scatter(event.xdata, event.ydata)
                ax.figure.canvas.draw()
            elif event.button == 2:
                # Do nothing
                print("scroll click")
            elif event.button == 3:
                # Do nothing
                print("right click")
            else:
                pass
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Plot some random scatter data
    ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10))
    
    fig.canvas.mpl_connect(
        'button_press_event', lambda event: onclick(event, ax2))
    plt.show()
    
    4 回复  |  直到 8 年前
        1
  •  10
  •   ImportanceOfBeingErnest    8 年前

    您可以检查鼠标按钮是否在之前移动鼠标后释放。因为对于缩放和平移,只有在没有发生之前的移动时,才可以调用函数来绘制新点。

    import numpy as np
    import matplotlib.pyplot as plt
    
    class Click():
        def __init__(self, ax, func, button=1):
            self.ax=ax
            self.func=func
            self.button=button
            self.press=False
            self.move = False
            self.c1=self.ax.figure.canvas.mpl_connect('button_press_event', self.onpress)
            self.c2=self.ax.figure.canvas.mpl_connect('button_release_event', self.onrelease)
            self.c3=self.ax.figure.canvas.mpl_connect('motion_notify_event', self.onmove)
    
        def onclick(self,event):
            if event.inaxes == self.ax:
                if event.button == self.button:
                    self.func(event, self.ax)
        def onpress(self,event):
            self.press=True
        def onmove(self,event):
            if self.press:
                self.move=True
        def onrelease(self,event):
            if self.press and not self.move:
                self.onclick(event)
            self.press=False; self.move=False
    
    
    def func(event, ax):
        print(event.xdata, event.ydata)
        ax.scatter(event.xdata, event.ydata)
        ax.figure.canvas.draw()
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Plot some random scatter data
    ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10))
    click = Click(ax2, func, button=1)
    plt.show()
    
        2
  •  5
  •   Rincewind    6 年前

    我意识到这是一个老问题,但我也遇到了同样的问题,我想我找到了一个巧妙的解决方案;然而,它目前仅适用于Qt后端(其他后端也可能存在类似的解决方案)。其思想是matplotlib在缩放或平移时更改光标形状,因此您可以对此进行检查。这是调整后的代码:

    import numpy as np
    import matplotlib
    matplotlib.use('qt5agg')
    import matplotlib.pyplot as plt
    
    
    def onclick(event, ax):
        # Only clicks inside this axis are valid.
        try: # use try/except in case we are not using Qt backend
            zooming_panning = ( fig.canvas.cursor().shape() != 0 ) # 0 is the arrow, which means we are not zooming or panning.
        except:
            zooming_panning = False
        if zooming_panning: 
            print("Zooming or panning")
            return
        if event.inaxes == ax:
            if event.button == 1:
                print(event.xdata, event.ydata)
                # Draw the click just made
                ax.scatter(event.xdata, event.ydata)
                ax.figure.canvas.draw()
            elif event.button == 2:
                # Do nothing
                print("scroll click")
            elif event.button == 3:
                # Do nothing
                print("right click")
            else:
                pass
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Plot some random scatter data
    ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10))
    
    fig.canvas.mpl_connect(
        'button_press_event', lambda event: onclick(event, ax2))
    plt.show()
    
    
        3
  •  4
  •   Paul Brodersen    8 年前

    区分单击和拖动/缩放(右键单击或左键单击)的一种方法是测量按钮按下和按钮释放之间的时间,然后在按钮释放上执行操作,而不是按下按钮。

    import numpy as np
    import matplotlib.pyplot as plt
    import time
    
    MAX_CLICK_LENGTH = 0.1 # in seconds; anything longer is a drag motion
    
    def onclick(event, ax):
        ax.time_onclick = time.time()
    
    def onrelease(event, ax):
        # Only clicks inside this axis are valid.
        if event.inaxes == ax:
            if event.button == 1 and ((time.time() - ax.time_onclick) < MAX_CLICK_LENGTH):
                print(event.xdata, event.ydata)
                # Draw the click just made
                ax.scatter(event.xdata, event.ydata)
                ax.figure.canvas.draw()
            elif event.button == 2:
                print("scroll click")
            elif event.button == 3:
                print("right click")
            else:
                pass
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Plot some random scatter data
    ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10))
    
    fig.canvas.mpl_connect('button_press_event', lambda event: onclick(event, ax2))
    fig.canvas.mpl_connect('button_release_event', lambda event: onrelease(event, ax2))
    plt.show()
    
        4
  •  0
  •   old-ufo    5 年前

    我的answe不适用于所有后端,但它适用于jupyter笔记本后端 nbAgg公司 ,类似于@Rincewind答案

    
    %matplotlib notebook
    import numpy as np
    import matplotlib.pyplot as plt
    import ipywidgets as wdg 
    
    def onclick(event, ax):
        # Only clicks inside this axis are valid.
        if event.inaxes != ax:
            return
        
        # Not adding points when zooming or paning
        ptr_type = str(fig.canvas.toolbar.cursor)
        pick = 'Cursors.POINTER'
        if ptr_type != pick:
            return
        
        if event.button == 1:
            print(event.xdata, event.ydata)
            # Draw the click just made
            ax.scatter(event.xdata, event.ydata)
            ax.figure.canvas.draw()
        elif event.button == 2:
            # Do nothing
            print("scroll click")
        elif event.button == 3:
            # Do nothing
            print("right click")
        else:
            pass
    
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Plot some random scatter data
    ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10))
    
    ka = fig.canvas.mpl_connect(
        'button_press_event', lambda event: onclick(event, ax2))
    plt.show()