Here's a functional demo that uses the WindowButtonMotionFcn property of a figure to capture the mouse position which is used to detect the closest (x,y) coordinates to the mouse within the axes. It continually updates a set of crosshairs that display the coordinates and updates two subplots showing the values along the selected row and column.
See inline comments for details.
Create the data and set up the plot
data = peaks(1000);
ax(1) = subplot(4,1,[1,2]);
imagesc(ax(1), data)
ax(1).YDir = 'Normal';
axis(ax(1),'equal')
axis(ax(1),'tight')
ax(1).Parent.WindowState = 'Maximized';
ax(1).Toolbar.Visible = 'off';
xlabel(ax(1), 'x axis lable')
ylabel(ax(1), 'y axis lable')
title(ax(1), 'Data')
gobj(1) = xline(min(xlim(ax(1))), 'k-');
gobj(2) = yline(min(ylim(ax(1))), 'k-');
ax(2) = subplot(4,1,3);
gobj(3) = plot(ax(2), 1:size(data,2), nan(1,size(data,2)), '-ko', 'MarkerSize', 4);
xlabel(ax(2), 'x index')
ylabel(ax(2), 'x value')
axis(ax(2), 'tight')
ax(3) = subplot(4,1,4);
gobj(4) = plot(ax(3), 1:size(data,1), nan(1,size(data,1)), '-ko', 'MarkerSize', 4);
xlabel(ax(3), 'y index')
ylabel(ax(3), 'y value')
axis(ax(3), 'tight')
set(ax(1).Parent,'windowbuttonmotionfcn', {@mouseMove, data, ax, gobj});
Define the WindowButtonMotionFcn
function mouseMove(~, ~, data, ax, gobj)
C = ax(1).CurrentPoint;
x = round(C(1,1));
y = round(C(1,2));
if x < ax(1).XLim(1) || x > ax(1).XLim(2) || y < ax(1).YLim(1) || y > ax(1).YLim(2)
return
end
gobj(1).Value = x;
gobj(1).Label = x;
gobj(2).Value = y;
gobj(2).Label = y;
gobj(3).YData = data(x,:);
title(ax(2), sprintf('X = %d', x))
gobj(4).YData = data(:,y);
title(ax(3), sprintf('Y = %d', y))
end
Addendum: turn on/off interactivity
Press the left mouse button to turn on interactivity and the right mouse button to pause it so that the crosshairs and subplots do not update with mouse motion.
WindowButtonMotionFcnInput = {@mouseMove, data, ax, gobj};
set(ax(1).Parent,'windowbuttondownfcn', {@startStopMouseMove, WindowButtonMotionFcnInput})
function startStopMouseMove(hobj,~,WindowButtonMotionFcnInput)
buttonID = hobj.SelectionType;
switch buttonID
case 'normal'
set(hobj,'windowbuttonmotionfcn', WindowButtonMotionFcnInput);
case 'alt'
set(hobj,'windowbuttonmotionfcn', []);
end
end
Best Answer