Get displayed axes limits for log scale
Show older comments
The below snippet makes a simple loglog plot and then sets the xlim to [0 3]. Because zero can't be shown on a log scale, the plot actually ends up showing data between x=1 and x=3.
When inspecting with ax.XLim or get(gca, 'XLim'), it returns [0 3], even though that doesn't match the currently displayed XLim.
Is there any way to access the currently displayed limits?
figure;
ax = axes;
loglog(1:2, 1:2)
xlim([0 3])
The fallback option is to iterate through ax.Children and find the minimum XData, but I'd like to avoid this as it becomes slow for large datasets.
Accepted Answer
More Answers (1)
There is (unfortunately) no way to query the actual limits in the case you described above, but based on your last sentence, I suspect what you want is the "data extents" not the "automatic limits".
The only solution I can think of is to use 'tight' limits instead of manually set limits. The resulting automatically selected limits will be tightly cropped to the data extents.
figure;
ax = axes;
loglog(1:2, 1:2)
xlim('tight')
xl = xlim
Unfortunately, this technique doesn't allow you to set just the lower-limit to 'auto' or 'tight', you need to set both the lower and upper limits. If you need to work-around that issue, I can think of two solutions:
Option 1: Query then change one value of the limits.
You could set the limits to tight, then set just the upper limit to a new value to achieve the effect above. Just beware that doing so could slow down your code. Specifically: querying and the immediately setting the limits can lead to performance issues as described on this documentation page: Optimize Code for Getting and Setting Graphics Properties.
figure;
ax = axes;
loglog(1:2, 1:2)
xlim('tight')
ax.XLim(2) = 3; % This will force a calculation of the limits, then change just the upper value.
xl = xlim
Option 2: Add a "dummy" and invisible object at the desired upper limits.
You can add a "dummy" data point to the axes at the desired upper limits, and force the upper limits to your desired value.
figure;
ax = axes;
loglog(1:2, 1:2)
line(3,1) % This single point will contribute to the limits, but has no marker or line, so you won't see it.
xlim('tight')
xl = xlim
2 Comments
Benjamin Kraus
on 28 May 2025
@William Graves: This is a pretty clever solution. As long as you are confident that none of the Camera properties have been modified (i.e. they are all in 'auto' mode), this approach is probably pretty reliable. Of course, this won't work if you've set the CameraTarget to be some other value, but I suspect that isn't an issue you need to worry about.
Categories
Find more on Log Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



