我有一个 Matlab 脚本,它在两个子图中绘制数据,并允许我使用 datatip 以交互方式单击任何数据点并输出该点的 x,y 信息。运行下面的代码,使用 datatip 单击数据点,然后按 Enter 键将在命令行窗口中输出该点的 x,y 值。我可以对任意数量的点执行此操作,直到循环结束或手动关闭图形窗口。图 1 和图 2 显示我分别单击左右子图中的一个点,信息可以在图的底部看到。 有没有办法让 Matlab 也输出我点击的子图?例如,它应该输出 x、y 和 1 或 2,其中 1 或 2 是子图索引。
clc
clearvars
close all
figure('units','normalized','Position',[0.15 0.45 0.7 0.55]);
for j1=1:2
sbp1(j1)=subplot(1,2,j1);
plot(1:1000,rand(1,1000),'k','linewidth',2);
set(gca,'fontsize',24);
end
linkaxes(sbp1,'x');
datacursormode on;
dcm_obj = datacursormode(gcf);
set(dcm_obj,'UpdateFcn',@myupdatefcn);
for rc11=1:10000
try
pause;
info_struct = getCursorInfo(dcm_obj);
if isfield(info_struct, 'Position')
mkc1=info_struct.Position;
fprintf('%.3f %.3f \n',mkc1(1),mkc1(2));
end
catch
break;
end
end
function output_txt = myupdatefcn(~,event_obj)
% ~ Currently not used (empty)
% event_obj Object containing event data structure
% output_txt Data cursor text
pos = get(event_obj, 'Position');
output_txt = {['x: ' num2str(pos(1))], ['y: ' num2str(pos(2))]};
end
一个简单的解决方案可能是使用轴的
UsderData
属性来保存轴的标识符。
可以添加
set(gca,'UserData',['Axes #' num2str(j1)]);
在创建子图的循环中。
然后您可以通过添加 UserData 中保存的字符串来更新打印位置的行
fprintf('%.3f %.3f \n%s\n',mkc1(1),mkc1(2),get(gca,'UserData'));
这是您的代码以及建议的解决方案。
clc
clearvars
close all
% figure('units','normalized','Position',[0.15 0.45 0.7 0.55]);
figure('units','normalized');
for j1=1:2
sbp1(j1)=subplot(1,2,j1);
plot(1:1000,rand(1,1000),'k','linewidth',2);
set(gca,'fontsize',24);
%
% Set the identifier of the axes in the UserData property
%
set(gca,'UserData',['Axes #' num2str(j1)]);
%
end
linkaxes(sbp1,'x');
datacursormode on;
dcm_obj = datacursormode(gcf);
set(dcm_obj,'UpdateFcn',@myupdatefcn);
% for rc11=1:10000
for rc11=1:10000
try
pause;
info_struct = getCursorInfo(dcm_obj);
if isfield(info_struct, 'Position')
mkc1=info_struct.Position;
% fprintf('%.3f %.3f \n',mkc1(1),mkc1(2));
%
% Print the position and the axes identifier
%
fprintf('%.3f %.3f \n%s\n',mkc1(1),mkc1(2),get(gca,'UserData'));
%
end
catch
break;
end
end
function output_txt = myupdatefcn(~,event_obj)
% ~ Currently not used (empty)
% event_obj Object containing event data structure
% output_txt Data cursor text
pos = get(event_obj, 'Position');
output_txt = {['x: ' num2str(pos(1))], ['y: ' num2str(pos(2))]};
end