How to highlight a point?
이전 댓글 표시
How to highlight a point?
The edge closest to the cursor, which is hovering over the figure, is temporariliy highlighted in (color).
댓글 수: 2
Adam Danz
2021년 11월 15일
Are you asking how to highlight the closest point to the cursor when the cursor is within the axes?
Gabriela Kurteva
2021년 11월 15일
답변 (1개)
Adam Danz
2021년 11월 15일
There are 3 steps to this process.
- Get the current point of the cursor
- Find the closest point to the cursor when the cursor is within the axes
- 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
Gabriela Kurteva
2021년 11월 15일
Adam Danz
2021년 11월 28일
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
카테고리
도움말 센터 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!