Search code examples
matlabaxisfigure

Matlab dynamic plot axis


At the moment I'm plotting two points in a grid and I'm using the xlim and ylim to force the scale of my plot, like this

enter image description here

but I'd like to have a plot that changes dynamically the axis depending on where is my target. This because my red point might go above xlim and ylim or way below of it, like these two cases.

enter image description here enter image description here

In the first one, the point is outside the window and therefore I cannot see it, while in the other case, the point is close to the origin of the plot and I'd like to see it more closely, like if I zoom in. For now I'm using

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

I think that to do what I need, I should use x,y somehow instead of a or a combination of the two in order to have a more dynamic range depending on the dimension of x,y. Is there any other easier and faster way to do that?


Solution

  • You can use axis handles and change the XData and YData properties to dynamically change axis limits. Consider the following sample code that plots a random data point and dynamically updates the axis limits,

    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