Search code examples
matlabplotscalematlab-figure

Prevent aggressive auto-scaling in Matlab


Say I have the following Matlab code:

figure;
a=plot(1:10); %A
pause();
set(a,'ydata',1:2:20); %B
pause();
set(a,'ydata',1:10); %C

At (A) the vertical range of my plot is [1,10].
At (B) the vertical range of my plot is [0,20].
At (C), the vertical range is once again [1,10].

I like that the plot auto-scales from step (A) to (B). I don't like the auto-scaling from (B) to (C) - it makes things jump around too much.

Is there a way to have set the plot's scale to expand but never shrink?

In my mind, this looks like:

set(gca,'XLimMode','auto_maxever');

Solution

  • To my knowledge, Matlab does not have a function such as you describe, however...

    You can set exactly the limits of X and Y by doing the following command:

    set(gca,'XLim',[x1 x2], 'YLim',[y1 y2]);
    

    A quick alias for the very same command is:

    axis([xmin xmax ymin ymax]);
    

    You might as well "freeze" the limits at any moment you like, by changing the XLimMode and YLimMode from Auto to Manual:

    figure();
    a=plot(1:10); %A
    pause();
    set(a,'ydata',1:2:20); %B
    pause();
    set(gca,'XLimMode','manual');
    set(gca,'YLimMode','manual');
    set(a,'ydata',1:10); %C
    

    Or you can use yet another alias, which does exactly the same:

    axis('manual');
    

    If data is being continuously acquired, consider saving the axis limits before each update and then performing manual scaling.