ayar - since you have four subplots (or axes) you will need to determine which axes your mouse cursor is hovering over before you try to determine the (x,y) coordinate for that axes. For example, suppose we plot four sine and cosine curves as
axesHandles = [];
hFig = figure;
xx = -2*pi:0.001:2*pi;
axesHandles = subplot(2,2,1);
plot(xx,sin(xx));
axesHandles = [axesHandles subplot(2,2,2)];
plot(xx,cos(xx));
axesHandles = [axesHandles subplot(2,2,3)];
plot(xx,5*sin(xx));
axesHandles = [axesHandles subplot(2,2,4)];
plot(xx,5*cos(xx));
With the above, we create the four subplots and store the handle to each axes. We then assign the WindowButtonMotionFcn as
set(hFig,'WindowButtonMotionFcn',@mouseMove);
hText = [];
where hText will be the handle to our text graphics object. (We hold on to this handle because we don't want to create a new text graphics object whenever we move the mouse.) Now are callback will look like
function mouseMove(hObject,eventdata)
figCurrentPoint = get(hObject, 'CurrentPoint');
position = get(hObject, 'Position');
xCursor = figCurrentPoint(1,1)/position(1,3);
yCursor = figCurrentPoint(1,2)/position(1,4);
isOverAxes = 0;
for k=1:length(axesHandles)
hAxes = axesHandles(k);
axesPos = get(hAxes,'Position');
minx = axesPos(1);
miny = axesPos(2);
maxx = minx + axesPos(3);
maxy = miny + axesPos(4);
if xCursor >= minx && xCursor <= maxx && yCursor >= miny && yCursor <= maxy
currentPoint = get(hAxes,'CurrentPoint');
x = currentPoint(2,1);
y = currentPoint(2,2);
textString = sprintf('(X,Y) = (%.6f,%.6f)', x, y);
if isempty(hText)
hText = uicontrol('Style', 'text','BackgroundColor', 'r',...
'FontSize',10,'FontWeight', 'bold','ForegroundColor', 'k');
end
set(hText,'Visible','on','Position', [figCurrentPoint(1,1) figCurrentPoint(1,2) 150 20], 'String', textString);
isOverAxes = true;
break;
end
if ~isOverAxes && ~isempty(hText)
set(hText,'Visible','off');
end
end
end
In the above, we get the current position of the mouse cursor and normalize it so that we can compare it to the normalized positions of the four axes. We loop over each axes until we find the one which satisfies
if xCursor >= minx && xCursor <= maxx && yCursor >= miny && yCursor <= may
We then get the current point within the axes which will be your "true" plotted data values. The text floats to the current position of the mouse cursor (rather than being static). See the attached for the full example.
Best Answer