在datatip中显示Matlab图例文本

时间:2015-07-06 11:43:13

标签: matlab matlab-figure

在某些情况下,除了x值和y值之外,让数据点的数据提示显示相应的图例条目会很方便。

如何让Matlab在绘制的数据点的数据提示中显示相应的图例文本?

2 个答案:

答案 0 :(得分:7)

您可以通过以编程方式提供自定义UpdateFcn来自定义数据提示中显示的数据。

示例:

fh = figure;
plot(rand(10,2));
legend('foo', 'bar');

datacursormode on;
dcm = datacursormode(fh);
set(dcm,'UpdateFcn',@customdatatip)

<强> customdatatip.m

function output_txt = customdatatip(obj,event_obj,str)
pos = get(event_obj, 'Position');
output_txt = {...
    ['X: ', num2str(pos(1),4)]...
    ['Y: ', num2str(pos(2),4)] ...
    ['legend: ', event_obj.Target.DisplayName]...
};

<强>输出

enter image description here

答案 1 :(得分:0)

可以设置自定义函数来创建数据提示文本。简单的方法是在图中右键单击并选择“选择 - ”或“编辑文本更新功能”。

该函数接收一个事件对象,其“Target”属性是所点击数据的句柄。使用图例时,文本存储在该数据的“DisplayName”属性中。

这是一个实现:

function output_txt = legendtip( 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).


try
    p = get(event_obj,'Target');
    legendtext = get((get(event_obj,'Target')),'DisplayName');
catch err
    disp(err.message)
end

pos = get(event_obj,'Position');

if ~isempty(title)
    output_txt = {legendtext ,...
        ['X: ' num2str(pos(1),4)],...
        ['Y: ' num2str(pos(2),4)]};
else
    output_txt = {['X: ' num2str(pos(1),4)],...
        ['Y: ' num2str(pos(2),4)]};
end

在2014b上测试。