MATLAB: Show mouse position in another subplot

copy mousemousemouse positionplotsubplot

I have a plot with two subplots, one frontal xray and one sagital xray, both with the same height, taken at the some moment. Hence y position in subplot 1 equals y position subplot 2.
I have to mark some points in subplot 1, but while moving my mouse in subplot 1, i want to show a (also moving) horizontal line in sublot 2, indicating the y value of the current mouse position from subplot 1. How can i make this?

Best Answer

You can use WindowButtonMotionFcn callback if figure. Run the following example
f = figure();
ax_up = subplot(2, 1, 1);
hold(ax_up);
ax_up.YLim = [0 2];
ax_down = subplot(2, 1, 2);
hold(ax_down);
ax_down.YLim = [0 2];
l = yline(0, 'r');
f.WindowButtonMotionFcn = @(fig, eve) btnCb(fig, eve, ax_up, l);
function btnCb(~, ~, ax_up, l_h)
y = ax_up.CurrentPoint(1, 2);
if (ax_up.YLim(1) < y) && (y < ax_up.YLim(2))
l_h.Value = y;
end
end