Link Matlab 子图中的不同数据源

Link different data sources in Matlab subplots

我想绘制纬度和经度数据以及另一种类型的数据(速度),记录在每个经纬度点。这基本上等同于

figure()
subplot(1,2,1); plot(lat,lon);
subplot(1,2,2); plot(t,y);

其中所有向量的长度都相同,t 是每次记录的时间戳(以秒为单位)。我希望能够 link 数据,这样当我在第一个子图中突出显示数据时,相应的数据就会在第二个子图中突出显示(反之亦然)。

但是,因为这两个子图没有共同的数据源(至少不是名字),我很难 linkdata 工作。

这是我尝试过的(没有 linkdata

function linkedexasmple()
close all

t = linspace(-2,2,100);
lat = sin(t);
lon = cos(t);
x = t;
y = exp(t);
M = [lat',lon',x',y'];

figure()
whos

subplot(1,2,1)
plot(M(:,1),M(:,2),'-x','XDataSource','M(:,1)','YDataSource','M(:,2)');
subplot(1,2,2)
plot(M(:,3),M(:,4),'-x','XDataSource','M(:,3)','YDataSource','M(:,4)');

%linkdata on
%linkdata showdialog
end

但是,如果我切换linkdata on,剧情就会完全变成这样。

如何在启用 link 的同时保留原始图?

作为最后一句话:我显然想稍后用参数(latlonxy)调用该函数。但是对于这个MWE,我认为这样会更容易。

有趣的问题。响应点击输入的回调函数比 linkdata 更自然。

下面的解决方案是一个快速的破解方法——您总是需要 select 子图 1 中的一个点。可以通过使用 MATLAB 的 ButtonDownFcn 函数并定义一个回调函数来使它更花哨子图已 select 编辑。

close all
clearvars

t = linspace(-2,2,100);
lat = sin(t);
lon = cos(t);
x = t;
y = exp(t);
M = [lat',lon',x',y'];

figure(1);

subplot(1,2,1)
plot(M(:,1),M(:,2),'-x','XDataSource','M(:,1)','YDataSource','M(:,2)');
subplot(1,2,2)
plot(M(:,3),M(:,4),'-x','XDataSource','M(:,3)','YDataSource','M(:,4)');

% Quick hack
while 1
    
    % Get coordinates of clicked point
    waitforbuttonpress;
    CP = get(gca,'CurrentPoint');
    x1 = CP(2,1);  % X-point
    y1 = CP(2,2);  % Y-point

    % Find index of closest point
    dists = (M(:,1)-x1).^2 + (M(:,2)-y1).^2; 
    [~,idx] = min(dists);

    % Replot base-figure to remove previously selected points
    figure(1);
    subplot(1,2,1)
    plot(M(:,1),M(:,2),'-x','XDataSource','M(:,1)','YDataSource','M(:,2)');
    subplot(1,2,2)
    plot(M(:,3),M(:,4),'-x','XDataSource','M(:,3)','YDataSource','M(:,4)');


    % Update both subplots
    subplot(1,2,1)
    hold on
    plot(M(idx,1),M(idx,2),'ro');
    hold off
    subplot(1,2,2)
    hold on
    plot(M(idx,3),M(idx,4),'ro');
    hold off
end

您可以将未记录的 BrushData 属性 与画笔 ActionPostCallback 一起使用。 BrushData 属性 是 01uint8 数组,其中 1 表示选择的数据点。在回调函数中,当其中一个子图被“刷”时,同时设置两个子图的BrushData

function linkedexample()
    t = linspace(-2,2,100);
    lat = sin(t);
    lon = cos(t);
    x = t;
    y = exp(t);

    fig = figure();
    subplot(1,2,1)
    p1 = plot(lat,lon);
    subplot(1,2,2)
    p2 = plot(x,y);

    % Bind callback function with the brush
    b = brush(fig);
    b.ActionPostCallback = {@onBrushAction};

    % callback function
    function onBrushAction(~, eventdata)
        set(p1, 'BrushData', eventdata.Axes.Children.BrushData)
        set(p2, 'BrushData', eventdata.Axes.Children.BrushData)
    end
end

结果:

这两篇文章 "Accessing plot brushed data" on Undocumented Matlab and this Mathwork post by its staff 提供了有关 BrushDataActionPostCallback 的更多信息。