# Is there a way to limit automatic Y or X axis scaling?

18 views (last 30 days)
Stephen Rhim on 8 Feb 2021
Edited: Fangjun Jiang on 9 Feb 2021
Is there a way to limit the autoscaling of the y-axis to a min and max? For example, I would like to limit my plot to [-10 10], but if all the data is between [-1 1], then the plot would autoscale the y-axis limits down closer to those values. If there are data points that go up to 100, the plot would show max y-axis limit of 10.

Fangjun Jiang on 8 Feb 2021
ylim('auto')
##### 2 CommentsShowHide 1 older comment
Fangjun Jiang on 9 Feb 2021
Would a few lines of code do this?
Once you have the data, you would know Ymin and Ymax, compare them with [-10,10] and you will know the range and then run ylim().
actually one line: ylim([max(min(y),-10), min(max(y),10)]

Walter Roberson on 8 Feb 2021
Axes limits might get recalculated if the figure or container (such as tab or uipanel) that they are in gets resized.
Therefore, you can create default SizeChangedFcn callbacks for figures and uitab and uipanel, that fish through the objects stored inside the container and reset the ylim if the ylim have become out of bounds. You would do this by, for example,
set(groot, 'defaultFigureSizeChangedFcn', @constrain_ylim)
You would also create a default Zoom PreActionCallback or perhaps PostActionCallback https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.internal.zoom.html#mw_25fc3acb-6068-41d7-bee9-bfcf904499d6 to force constraints on zooming.
You would also create some kind of default chart interactivity, but I am not familiar with the mechanism for those; https://www.mathworks.com/help/matlab/creating_plots/control-axes-interactions.html
Or you could create a default AxesCreateFcn callback that would create a listener for axes the YLim property changing and force it back into desired bounds.
The idea on all of these is that you cannot directly constrain the automatic axes limits, but you can catch the circumstances under which the axes limits would change, and run some code to force the limits to be what you prefer.
Yes, this is a nuisance, and might not work all that well without going to a lot of hassle. But it is "a way", so it would have been incorrect for me to say "No, there is no way".

R2018b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!