How do I determine the data value or point closest to where my mouse clicks?

16 visualizaciones (últimos 30 días)
For example, I want to select a point on the plot and display either a closest data point or the index to the closest data point.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 27 de En. de 2020
Editada: MathWorks Support Team el 27 de En. de 2020
Below is an example of how you can calculate the closest X and Y values to the mouse click.
% Generate a plot
X = linspace(-2*pi,2*pi,20);
Y = 5*sin(X)./X;
plot(X,Y,'x-')
axis equal
title('Click in the plot once...')
% Click the mouse in the plot - Using
% waitforbuttonpress for this example.
waitforbuttonpress;
% Determine the current point
Cp = get(gca,'CurrentPoint');
Xp = Cp(2,1); % X-point
Yp = Cp(2,2); % Y-point
% Find the minimum distance to determine
% which point is closest to the mouse
% click
[dp,Ip] = min((X-Xp).^2+(Y-Yp).^2);
% Extract the closest coordinate values
Xc = X(Ip);
Yc = Y(Ip);
% Add some text
str1 = sprintf('\\leftarrow You clicked here.');
str2 = sprintf(['Closest point: (%f,%f) \\rightarrow'],Xc,Yc);
ht(1) = text(Xp,Yp,str1,'Clipping','off');
ht(2) = text(Xc,Yc,str2,'Clipping','off', ...
'HorizontalAlignment','right');
set(ht,'FontSize',8,'Color','red')
Here is an example of code that makes use of a context menu. Run the code, and right-click on the line:
x=0:.01:2*pi;
y=sin(x);
h=plot(x,y);
hc=uicontextmenu;
hm=uimenu('parent',hc);
set(h,'uicontextmenu',hc);
set(gcf,'windowbuttondownfcn', ...
'pt=get(gca,''currentpoint'');set(hm,''label'',[num2str(pt(1,1)) '', '' num2str(pt(1,2))])')

Más respuestas (0)

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by