Get index of an x, y data point via user selection in a plot.

69 views (last 30 days)
I have two vectors, x and y shown in a scatter plot. Each value is the result of an evaluation and has its own data set.
i. e. x(1) = evalX(DataSet_1), x(2) = evalX(DataSet_2), ... the same for y
i. e. y(1) = evalY(DataSet_1), y(2) = evalY(DataSet_2), ...
Now I want to have a look in the data sets of points of interest. That is, I'd like to klick a data point in the plot figure and want to get the index of the data point.
The only Idea I have is to write a callback function returning the values of a data point (u and v) and plug them in find(x == u). But the data points are double so checking for equality might be not ideal? Also I find this solution not very elegant.
Any Ideas?
  1 Comment
Riccardo Scorretti
Riccardo Scorretti on 8 Apr 2022
Hi. I would suggest to plot all of the points with a single call to plot, define a callback associated with the object created by the function plot (not with the figure), and then selecting the point by looking for the minimal distance between the (x,y) coordinates and the set of points. That should be robust.

Sign in to comment.

Answers (3)

KSSV on 8 Apr 2022
Edited: KSSV on 8 Apr 2022
% random points for demo
x = rand(10,1) ;
y = rand(10,1) ;
% Scatter plot
% clicks by the user
[xi,yi] = getpts() ;
% get the index
idx = knnsearch([x y],[xi yi])

Riccardo Scorretti
Riccardo Scorretti on 8 Apr 2022
I would do like that (thanks to KSSV, I didn't know functions scatter and knnsearch):
function demo
x = rand(10,1);
y = rand(10,1);
hndl = scatter(x, y);
hndl.ButtonDownFcn = @myCallback;
function myCallback(src, evt)
xi = evt.IntersectionPoint(1);
yi = evt.IntersectionPoint(2);
idx = knnsearch([x y], [xi yi])
By programming myCallback as a nested function, it has access to variables x and y. In my opinion, it is better if the callback is invoked only when the user clicks on any of the points (and not anywhere in the figure). Of course, in this way it is mandatory to use a callback, which perhaps you absolutely want to avoid.

Martin Danz
Martin Danz on 8 Apr 2022
Thanks for the suggestions. It seem's I do not have the toolbox required by knnsearch.
However I came up with a workaround using 3D-Plot scatter3, defining the index as z-values and setting the view to 2D. If I now hover the mouse over a data point, z gives me exactly what I want.
Obviously the workaround will not work for 3D Plots, maybe mathworks will implement a similar functionality in future releases?
N = 13;
x = rand(N, 1);
y = rand(N, 1);
scatter_wIndex(x, y)
function h = scatter_wIndex(x, y, varargin)
z = 1:length(1:length(x));
scatter3(x, y, z, varargin{:})




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!