You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让MATLAB Datatip输出Subplot(子图)索引信息?

如何在MATLAB数据点点击时输出子图索引

可以通过以下修改实现点击数据点时同时输出子图索引,核心是利用数据光标事件对象获取目标子图,再匹配索引:

修改后的完整代码

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') && isfield(info_struct, 'Target')
            % 获取点击的子图对象
            clicked_axes = ancestor(info_struct.Target, 'axes');
            % 匹配子图索引
            subplot_idx = find(sbp1 == clicked_axes);
            mkc1=info_struct.Position;
            fprintf('子图索引: %d | x: %.3f | y: %.3f \n',subplot_idx, 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');
% 获取子图索引并添加到datatip显示
clicked_axes = ancestor(event_obj.Target, 'axes');
subplot_idx = find(sbp1 == clicked_axes);
output_txt = {['子图索引: ' num2str(subplot_idx)],...
              ['x: ' num2str(pos(1))],...
              ['y: ' num2str(pos(2))]};
end

关键修改说明

  • 在主循环中,通过info_struct.Target获取点击的线条对象,再用ancestor(info_struct.Target, 'axes')找到该线条所属的子图对象。
  • 对比预先保存的子图数组sbp1,用find函数匹配得到子图索引。
  • 在myupdatefcn函数中做同样的操作,把索引添加到数据提示框(Datatip)中,同时在命令行输出时也包含索引信息。

修改后,点击任意子图中的数据点,命令行窗口会同时输出子图索引、x值和y值,数据提示框也会同步显示子图索引。

内容的提问来源于stack exchange,提问作者Guddu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:05:24