Matlab动态绘图轴

Matlab dynamic plot axis

目前我正在网格中绘制两个点,我正在使用 xlimylim 来强制我的绘图比例,就像这样

但我想要一个根据我的目标位置动态改变轴的图。这是因为我的红点可能高于 xlimylim 或低于它,就像这两种情况。

第一种情况下,点在window之外,所以我看不到,而另一种情况下,点靠近绘图的原点,我想看看它更紧密,就像我放大一样。 现在我正在使用

plot(x,y,'.','MarkerSize',20,'Color','r');
xlim([-a a]);
ylim([-a a]);

我认为,为了满足我的需要,我应该使用 x,y 而不是 a 或两者的组合,以便根据 [ 的维度获得更大的动态范围=15=]。 还有其他更简单快捷的方法吗?

您可以使用轴句柄并更改 XDataYData 属性以动态更改轴限制。考虑以下绘制随机数据点并动态更新轴限制的示例代码,

h = figure;
% get axis handle
ax = gca(h);
set(ax, {'XLim', 'YLim'}, {[-1 1], [-1 1]});

XY = [];

for i = 1:100
    % generate random data point
    xy = 2*randn(1, 2);
    XY = cat(1, XY, xy);

    % get min and max values of points so far
    minVals = min(XY, [], 1);
    maxVals = max(XY, [], 1);

    % plot the data point
    scatter(xy(1), xy(2), 'b*');
    hold on;

    % update the axis limits dynamically
    set(ax, {'XLim', 'YLim'}, {[minVals(1)-1 maxVals(1)+1], [minVals(2)-1 maxVals(2)+1]});
    % pause so that you can see the plot update
    pause(0.5);
end

我认为您正在寻找 axis tight 命令。根据文档,它的作用是

Fit the axes box tightly around the data by setting the axis limits equal to the range of the data.

...

The limits automatically update to incorporate new data added to the axes. To keep the limits from changing when using hold on, use axis tight manual.

这是一个演示:

y = randi(21,10,1)-11;
figure(); hP = plot(NaN(10,1),NaN(10,1),'-o'); axis tight; grid minor;
for ind1 = 1:numel(x)
  hP.XData(ind1) = x(ind1);
  hP.YData(ind1) = y(ind1);
  pause(0.5);
end

注意轴限制是如何自动改变的: