silx
silx copied to clipboard
[plot] closest function for item
Item provides a pick method to reach data index at a specific location.
This is based on the backend and can't be used for position far away from the item.
It would be good to provide a closest function.
- At least taking a x/y position
- At least processing only visible elements
- At least computing distances based on the display (then taking care of log scale)
- At least for curve items
- Returning at least the closest data index, and computed distance
Here is my current implementation.
It do not manage the log scale, nor the visible data.
def __closest(self, curve, x, y):
"""Returns the closest point from a curve item"""
xx = curve.getXData()
yy = curve.getYData()
if xx is None or len(xx) > 0:
return None, None
xdata, ydata = self.__plot.pixelToData(x, y)
xcoef, ycoef = self.__plot.pixelToData(1, 1)
if xcoef == 0:
xcoef = 1
if ycoef == 0:
ycoef = 1
xcoef, ycoef = 1 / xcoef, 1 / ycoef
dist = ((xx - xdata) * xcoef) ** 2 + ((yy - ydata) * ycoef) ** 2
index = numpy.nanargmin(dist)
xdata, ydata = xx[index], yy[index]
pos = self.__plot.dataToPixel(xdata, ydata)
if pos is None:
return None, None
xdata, ydata = pos
dist = numpy.sqrt((x - xdata) ** 2 + (y - ydata) ** 2)
return index, dist