Get data point that was clicked on in graph

135 次查看(过去 30 天)
I have a plot on a GUIDE GUI that gives some measurement made from frames in a video. What my user wants is to click on a point in the plot and display the frame from the video that corresponds to that point in the graph. I was told from Mathworks tech support that this is not possible. But is it really impossible? They told me I could setup a callback function for the graph (axes) and then when I clicked on it I would go into the callback function and I could get the whole XData and YData vectors but I could not get the one point I clicked on, even though it shows up in the graph with the X and Y as data tips. So for example:
x=1:8;
y = rand(1, numel(x));
plot(x, y, 'b.-', 'MarkerSize', 15);
grid on;
And let's say I clicked on the point at x=6. I would go into the callback and be able to get the full 8-element x and y vectors, but the callback function would have no idea where I clicked or what the closest data point to that location is. Is that really true? I find that hard to believe. Is there any easy way to find out what vector element was clicked on? Or do I have to call on the almighty Yair Altman for a favor?

回答(1 个)

Yair Altman
Yair Altman 2023-1-30
At your service :-)
t=0:.01:5; y=sin(t); hPlot=plot(t,y);
hPlot.ButtonDownFcn = @(h,e) disp(e.IntersectionPoint);
Now whenever you click on the plot line, it will display the clicked coordinates [x,y,z]. The event data's IntersectionPoint is a 1x3 vector. Of course, to accept mouse clicks, the plot-line's HitTest property must be set to 'on' (or true).
  5 个评论
Diptangshu Paul
Diptangshu Paul 2024-10-17
Dear Altman, this is a very simple code, yet a beautiful solution to a big problem. However for my purpose, I need to store these coordinates into a variable. How can it be done?
Yair Altman
Yair Altman 2024-10-17
You can set the ButtonDownFcn callback property value to a handle to a function in your code, and in that function you can access the event's IntersectionPoint in a variable and then use it as you need.
If you need help with this, read the Matlab documentation about using callback functions.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by