matlab图中的数据提示自定义

时间:2012-08-23 21:16:11

标签: matlab matlab-figure

我有一个包含多个图的图表,每个图都来自不同的源文件。我希望数据提示告诉我(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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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(我稍后会假设),但我没有在任何早期版本上尝试过它。

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