MATLAB: Can I use arrows to move Data Tips on scatter plots

data tipMATLABscatter

I know that when using the plot function with data tips you can use the arrow keys to move the data tip through the data set. Is there a way to do this with scatter plots as well? I need to be able to define the marker color individually, which is why I'm using scatter instead of plot.

Best Answer

Hi David,
Edit: I have updated the code and it works. It's better if the callback is on KeyPressFcn, especially for plots with many points.
I have taken part of code from Adam's answer, thanks Adam!
% clear functions % On the second run, datatip will continue from where it stopped the previous run, if you mind that, uncomment this line
fig = figure('KeyPressFcn', @ArrowKeyPressed);
ax = axes(fig);
x = linspace(0,2*pi,25);
y = cos(x) + rand(1,numel(x))/2;
sz = (abs(sin(x))*4+1)*25;
c = linspace(1,10,numel(x));
scatter(ax, x,y,sz,c,'filled','MarkerEdgeColor', 'k');
grid on
It is possible to write a callback for the figure that would detect arrow key presses
function ArrowKeyPressed(Source, Event)
persistent dtNum
if isempty(dtNum) % Initialise the variable
dtNum = 0;
end
% Get axes handle
ax = findall(Source, 'Type', 'axes');
% Get the scatter object
h = findall(ax, 'Type', 'scatter');
% Get the datatips associated with scatter object
datatipObjs = findobj(h,'Tag','datatip');
% Get the number of points
numPoints = length(h.XData); % assuming x is a vector
% Setting up the counter
switch Event.Key
case 'leftarrow'
if dtNum > 1
dtNum = dtNum - 1;
else
dtNum = 1;
end
case 'rightarrow'
if ~isequal(dtNum, numPoints)
dtNum = dtNum + 1;
end
otherwise
return
end
% Removing the previous (all if there are more) and creating the next datatip
if isvalid(datatipObjs); delete(datatipObjs); end
datatip(h, h.XData(dtNum), h.YData(dtNum));
end