How to highlight a point?

20 views (last 30 days)
Gabriela Kurteva
Gabriela Kurteva on 15 Nov 2021
Commented: Adam Danz on 28 Nov 2021
How to highlight a point?
The edge closest to the cursor, which is hovering over the figure, is temporariliy highlighted in (color).
  2 Comments
Gabriela Kurteva
Gabriela Kurteva on 15 Nov 2021
Yes, that's what i meant.

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 15 Nov 2021
There are 3 steps to this process.
  1. Get the current point of the cursor
  2. Find the closest point to the cursor when the cursor is within the axes
  3. Temporarily highlight the point
Step 1 can be achieved in several ways. In this demo I use a WindowButtonMotion function. See this answer to learn how to use a Pointer Manager instead.
In step2, the demo deteremines whether the current point is within the axes or not using the axis limits (XLim, YLim). hypot is used to find the minimum distance between the current point and all points in the axes.
Only points that are defined by objects that have XData and YData properties are considered.
The previous highlighted point(s) are removed and the new closest point is highlighted.
% Create base figure with two line objects
fig = figure();
ax = axes(fig);
plot(ax, rand(1,50), rand(1,50), 'r*');
hold(ax, 'on')
plot(ax, rand(1,50), rand(1,50), 'b^');
axis equal % if axes aspect ratios are not equal, results may appear strange but correct
grid on
% Set the WindowButtonMotionFcn to respond to mouse movement over the figure.
fig.WindowButtonMotionFcn = {@WindowButtonMotion, ax};
% Define the WindowButtonMotionFcn callback function
% This will respond to mouse movement within the figure.
function WindowButtonMotion(~, ~, ax)
% Determine if mouse is within axes
cp = ax.CurrentPoint;
isInAxes = cp(1,1) >= ax.XLim(1) && ...
cp(1,1) <= ax.XLim(2) && ...
cp(1,2) >= ax.YLim(1) && ...
cp(1,2) <= ax.YLim(2);
% Delete previous highligh
delete(findobj(ax, 'tag', 'ptHighlight'))
if isInAxes
% Get all coordinates in axes
% This only references objects with XData and YData props
objs = findobj(ax, '-property', 'xdata');
x = horzcat(objs.XData);
y = horzcat(objs.YData);
% find index to nearest point to cursor
[~, idx] = min(hypot(x-cp(1,1), y-cp(1,2)));
% highlight point
holdstate = ishold(ax);
hold(ax, 'on')
% Set size, color, transparency, etc, of highlighted marker
scatter(x(idx), y(idx), 110, 'yellow', 'filled','o', ...
'MarkerFaceAlpha', .4, ...
'MarkerFaceColor', 'yellow', ...
'MarkerEdgeColor','k', ...
'Tag', 'ptHighlight')
drawnow()
% return hold state
if ~holdstate
hold(ax, 'off')
end
end
end
  3 Comments
Adam Danz
Adam Danz on 28 Nov 2021
Add the callback function by right-clicking the figure background in design mode and selecting the desired callback function.
This link should help get you started

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!