Distinguish button_press_event from drag and zoom clicks in matplotlib

2024/10/13 17:12:57

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()
Answer

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()
https://en.xdnf.cn/q/69509.html

Related Q&A

String reversal in Python

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?I a…

Python: passing functions as arguments to initialize the methods of an object. Pythonic or not?

Im wondering if there is an accepted way to pass functions as parameters to objects (i.e. to define methods of that object in the init block).More specifically, how would one do this if the function de…

Encrypt and Decrypt by AES algorithm in both python and android

I have python and android code for AES encryption. When I encrypt a text in android, it decrypt on python successfully but it can’t decrypt in android side. Do anyone have an idea?Python code :impo…

How to conditionally assign values to tensor [masking for loss function]?

I want to create a L2 loss function that ignores values (=> pixels) where the label has the value 0. The tensor batch[1] contains the labels while output is a tensor for the net output, both have a …

Assign Colors to Lines

I am trying to plot a variable number of lines in matplotlib where the X, Y data and colors are stored in numpy arrays, as shown below. Is there a way to pass an array of colors into the plot function,…

How to display multiple annotations in Seaborn Heatmap cells

I want seaborn heatmap to display multiple values in each cell of the heatmap. Here is a manual example of what I want to see, just to be clear:data = np.array([[0.000000,0.000000],[-0.231049,0.000000]…

ImportError: No module named lxml on Mac

I am having a problem running a Python script and it is showing this message:ImportError: No module named lxmlI suppose I have to install somewhat called lxml but I am really newbie to Python and I don…

Pandas Rolling window Spearman correlation

I want to calculate the Spearman and/or Pearson Correlation between two columns of a DataFrame, using a rolling window.I have tried df[corr] = df[col1].rolling(P).corr(df[col2]) (P is the window size)b…

Python string splitlines() removes certain Unicode control characters

I noticed that Pythons standard string method splitlines() actually removes some crucial Unicode control characters as well. Example>>> s1 = uasdf \n fdsa \x1d asdf >>> s1.splitlines(…

Get only HTML head Element with a Script or Tool

I am trying to get large amount of status information, which are encoded in websites, mainly inside the "< head >< /head >" element. I know I can use wget or curl or python to get…