自定义3D对象的数据光标

时间:2020-06-22 06:17:19

标签: matlab matlab-figure datatip datatipfunction

比方说,我在MATLAB中使用surf / mesh函数绘制了许多球体。

我想显示自定义数据值,而不是x,y,z。对于不同的球体,所有值将有所不同,并且单击特定球体上的任何点都应显示相同的数据。参考图。我该如何实现?

到目前为止,我正在考虑使用Surface属性'tag'为每个球体分配唯一的字符串。有更好的方法吗?

enter image description here

[x,y,z] = sphere;
a=[3 1 3 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');
s1.Tag = '1';

我应该如何继续使用自定义数据光标功能以实现自定义功能?

1 个答案:

答案 0 :(得分:2)

datacursor函数是figure的属性,因此窍门是为该图分配datatip更新函数。

在每个球体/图形对象的Tag属性中放置自定义信息对于您要实现的目标来说是个好主意。

首先定义更新功能。将以下文件保存在datatip_sphere.m下,并确保该文件在Matlab路径中可见:

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 };

有了这一点,现在让我们绘制两个球体,并确保游标功能显示所需内容:

% 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 ;

很明显,重要的几行是最后4行,您在其中为每个图形对象分配一个Tag,特别是在最后两行中,将自定义光标更新功能分配给该图形。


很酷,现在您的数据提示将始终显示分配给该对象的名称/标签,无论其位置如何:

datatip animation