Matlab图中数据提示的自定义

4

我有一个图形,其中包含几个绘图,每个绘图都来自不同的源文件。我希望数据提示能告诉我(X,Y)以及源文件的名称。到目前为止,我最好的尝试(没有成功)是这样的:

dcm = datacursormode(gcf);
datacursormode on;
set(dcm,'UpdateFcn',[@myfunction,{SourceFileName}]);

在这种情况下,默认函数是 myfunction,该函数在本消息末尾粘贴,并在此处解释:http://blogs.mathworks.com/videos/2011/10/19/tutorial-how-to-make-a-custom-data-tip-in-matlab/。最后,SourceFileName 是一个字符串,它包含源文件的名称。

是否有更简单(或正确)的方法来完成这个任务?

提前致谢。

function output_txt = myfunction(~,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');
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

end
2个回答

3
p=plot( x,y);
setappdata(p,'sourceFile_whatever', SourceFileName)  

dcm = datacursormode(gcf);
datacursormode on;
set(dcm, 'updatefcn', @myfunction)

在回调函数中:

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).
% event_obj

dataIndex = get(event_obj,'DataIndex');
pos = get(event_obj,'Position');

output_txt = {[ 'X: ',num2str(pos(1),4)],...
    ['Y: ',num2str(pos(2),4)]};

try
    p=get(event_obj,'Target');
    output_txt{end+1} = ['SourceFileName: ',getappdata(p,'sourceFile_whatever')];
end


% 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

0

虽然我来晚了,但我想回答这个问题,以防有人看到它并发现它仍然有用。

更改

set(dcm,'UpdateFcn',[@myfunction,{SourceFileName}]);

set(dcm,'UpdateFcn',{@myfunction,SourceFileName});

然后回调函数可以更改为以下内容。(注意:我删除了Z坐标,因为问题只提到了X和Y。)
function output_txt = myfunction(~,event_obj,filename)
% Display the position of the data cursor
% obj          Currently not used (empty)
% event_obj    Handle to event object
% filename     Name of the source file (string)
% output_txt   Data cursor text string (string or cell array of strings).

pos = get(event_obj,'Position');
output_txt = {['X: ',num2str(pos(1),4)],...
    ['Y: ',num2str(pos(2),4)],...
    ['Source: ',filename]};

end

显然,在回调函数中,您可以根据需要对格式进行任何更改,以便以不同的格式获取字符串。

通过更改回调函数的函数签名并更新set(dcm,...行以匹配(附加参数放在{}内,用逗号分隔),您可以向回调函数添加任意数量的参数。这适用于R2013a(我假设后来的版本也是如此),但我没有在任何早期版本上尝试过。

编辑:回调函数可能还需要在使用它的代码相同的文件中定义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接