I have a simple code that shows two subplots, and lets the user left click on the second subplot while recording the x,y
coordinates of those clicks.
The problem is that clicks to select a region to zoom and to drag the subplot are also identified as left clicks.
Is there a way to distinguish and filter out these left clicks?
import numpy as np
import matplotlib.pyplot as pltdef 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 madeax.scatter(event.xdata, event.ydata)ax.figure.canvas.draw()elif event.button == 2:# Do nothingprint("scroll click")elif event.button == 3:# Do nothingprint("right click")else:passfig, (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()
You may check if the mouse button is released after the mouse has previously been moved. Since for zooming and panning, this would be the case you may call the function to draw a new point only when no previous movement has happened.
import numpy as np
import matplotlib.pyplot as pltclass Click():def __init__(self, ax, func, button=1):self.ax=axself.func=funcself.button=buttonself.press=Falseself.move = Falseself.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=Truedef onmove(self,event):if self.press:self.move=Truedef onrelease(self,event):if self.press and not self.move:self.onclick(event)self.press=False; self.move=Falsedef 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()