MATLAB: How to obtain the handle to a datatip in MATLAB

MATLAB

I am placing datatips on my graph and have created a custom 'Update Function' to plot a line through the points marked by the datatips. I would like to obtain a handle to my datatip in order to identify which line must be updated when I move a datatip.

Best Answer

The 'event_obj' input to the 'Update Function' is actually a handle to the datatip object. The example 'Update Function' below illustrates how to store these handles in a persistent variable in order to identify which datatip is currently being updated.
function output_txt = myfunction(obj,event_obj)
% Display the position of the data cursor
% obj Currently not used (empty)
% event_obj Handle to event object
% output_txt Data cursor text string (string or cell array of strings).
pos = get(event_obj,'Position');
persistent line_handles %handles to the plotted lines
persistent datatip_objects %handles to the datatips on the graph
n = numel(datatip_objects);
found_match = 0;
count = 0;
%Look for the current datatip in our list of known datatips
while ~found_match && count < n
count = count+1;
found_match = (event_obj == datatip_objects{count});
end
%plot a line through the point of interest
x_val = pos(1);
l = line([x_val-1 x_val x_val+1], [pos(2), pos(2), pos(2)]);
if found_match
delete(line_handles(count)); %delete previous line
line_handles(count)=l; %save the handle to this line
else
datatip_objects{n+1}=event_obj; %this datatip is new, store its handle
line_handles(n+1)=l; %store the line handles as well
end
%code from the standard 'Update Function'
output_txt = {['X: ',num2str(pos(1),4)],...
['Y: ',num2str(pos(2),4)]};
% If there is a Z-coordinate in the position, display it as well
if length(pos) > 2
output_txt{end+1} = ['Z: ',num2str(pos(3),4)];
end
Related Question