The datacursor function is an attribute of the figure
, so the trick is to assign the datatip update function to the figure.
Placing the custom information for each sphere/graphic object in its Tag
property is a good idea for what you want to achieve.
Let's define the update function first. Save the following file under datatip_sphere.m
and make sure it is visible in the Matlab path:
function output_txt = datatip_sphere(~,event_obj)
% Display the tag of the cursor target
% obj Currently not used (empty)
% event_obj Handle to event object
% output_txt Data cursor text string (string or cell array of strings).
output_txt = { event_obj.Target.Tag };
Armed with that, now let's draw two spheres and make sure the cursor function displays what you want:
% retrieve the handle of the figure used for sphere display
% (better than calling 'gca' in datacursormode(hfig)
hfig = figure ;
% Draw your objects
[x,y,z] = sphere;
a=[3 1 3 1] ;
b=[5 6 4 1] ;
s1 = surf(x*a(1,4)+a(1,1),y*a(1,4)+a(1,2),z*a(1,4)+a(1,3),...
'FaceColor', [1 0 0],'FaceLighting','flat','EdgeColor','none','Facealpha',0.5);
hold on
s2 = surf(x*b(1,4)+b(1,1),y*b(1,4)+b(1,2),z*b(1,4)+b(1,3),...
'FaceColor', [0 0 1],'FaceLighting','flat','EdgeColor','none','Facealpha',0.5);
axis equal
% Add a tag to each object
s1.Tag = 'This is sphere 1';
s2.Tag = 'This is sphere 2';
% Now force the figure datatip function to your custom version
dcm = datacursormode(hfig) ;
dcm.UpdateFcn = @datatip_sphere ;
Obviously, the important lines are the last 4 lines, where you assign a Tag
for each of your graphic object, and specially the last two lines where you assign your custom cursor update function to the figure.
Cool, now your datatip will always display the name/tag assigned to the object, regardless of their position:
