使用单个滑块更新 Matlab 中的多个绘图

Using a single slider to update multiple plots in Matlab

我正在编写一个脚本,它将创建 2 个子图,并且有一个滚动两个图的 x 轴的滑块,或者 2 个单独控制每个子图 x 轴的滑块。

我一直在为我的滑块使用 Steven Lords FileExchange scrolling plot demo 的改编版本。

现在它只会更新最近的情节(因为它目前正在其回调函数中使用 gca)。我试过用我想要的轴(变量 first_plotsecond_plot)替换 gca 但这似乎不起作用。

那么我的问题是,我应该如何调整这个函数来控制两个地块或单独控制每个地块?这是我正在编写的脚本示例:

x=0:1e-2:2*pi;
y=sin(x);
dx=2;
first_plot = subplot(2,1,1);
plot(x, y);
scrollplot(dx, x)
%Plot the respiration and probe data with scrolling bar

second_plot = subplot(2,1,2);
plot(x, y); 
scrollplot(dx,x)

% dx is the width of the axis 'window'
function scrollplot(dx, x)
a=gca;
% Set appropriate axis limits and settings
set(gcf,'doublebuffer','on');

set(a,'xlim',[0 dx]);

% Generate constants for use in uicontrol initialization
pos=get(a,'position');
Newpos=[pos(1) pos(2)-0.1 pos(3) 0.05];
% This will create a slider which is just underneath the axis
% but still leaves room for the axis labels above the slider
xmax=max(x);
%S= set(gca,'xlim',(get(gcbo,'value')+[0 dx]));   
S=['set(gca,''xlim'',get(gcbo,''value'')+[0 ' num2str(dx) '])'];
% Setting up callback string to modify XLim of axis (gca)
% based on the position of the slider (gcbo)

% Creating Uicontrol
h=uicontrol('style','slider',...
    'units','normalized','position',Newpos,...
    'callback',S,'min',0,'max',xmax-dx);
end

谢谢!

您快完成了,但是当您仅从一组轴修改代码时存在一些结构性问题。

要做的关键是将回调函数从字符串更改为实际的本地函数。这使得处理回调更加简单!

我已经调整了您的代码以使用两个(或更多)轴。注意我们只需要设置一次滚动条!您正在为每个轴设置它(滚动条彼此堆叠)并且两个滚动条仅在 gca 上运行。仅命名坐标轴不足以更改 gca,您必须使用这些变量!我已将轴分配给数组以便于操作。

详情请看评论:

x=0:1e-2:2*pi;
y=sin(x);
% dx is the width of the axis 'window'
dx=2;

% Initialise the figure once, and we only need to set the properties once
fig = figure(1); clf;
set( fig, 'doublebuffer', 'on'); 
% Create a placeholder for axes objects
ax = gobjects( 2, 1 );

% Create plots, storing them in the axes object
ax(1) = subplot(2,1,1);
plot(x, y);

ax(2) = subplot(2,1,2);
plot(x, y); 

% Set up the scroller for the array of axes objects in 'ax'
scrollplot( dx, x, ax)

function scrollplot( dx, x, ax )
    % Set appropriate axis limits
    for ii = 1:numel(ax)
        set( ax(ii), 'xlim', [0 dx] );
    end

    % Create Uicontrol slider
    % The callback is another local function, this gives us more
    % flexibility than a character array.
    uicontrol('style','slider',...
        'units', 'normalized', 'position', [0.1 0.01 0.8 0.05],...
        'callback', @(slider, ~) scrollcallback( ax, dx, slider ), ...
        'min', 0, 'max', max(x)-dx );
end

function scrollcallback( ax, dx, slider, varargin )
    % Scroller callback loops through the axes objects and updates the xlim
    val = slider.Value;
    for ii = 1:numel(ax)
        set( ax(ii), 'xlim', val + [0, dx] );
    end
end