Given an axis within a figure, compute what the x and y axis limits would be if the axis extended to the edges of the figure.
Demo: See inline comments that explain each step. The variables newXLim and newYLim contain the extended axis limits.
It uses randomly placed axes with randomly set axis limits. After computing the expanded axis limits a second axis is created set to fill the figure and contains the extended axis limits. This axis is used to plot lines that should align with the original axis limits to confirm successful conversion. The axis limits to the exapanded axes are shown in the upper, left corner.
ax = axes(fig,'Units','Normalize',...
'Position', [rand(1,2)*.4+.05, rand(1,2)*.2+.35], ...
xlim(ax,sort(rand(1,2)*100))
ylim(ax,sort(rand(1,2)*100))
axPos = ax.InnerPosition;
axMarg = [axPos(1:2),figPos(3:4) - (axPos(1:2)+axPos(3:4))];
xyFactor(1) = range(xl) / axPos(3);
xyFactor(2) = range(yl) / axPos(4);
xyMargDataUnits = axMarg.*xyFactor([1,2,1,2]);
newXLim = [xl(1)-xyMargDataUnits(1), xl(2)+xyMargDataUnits(3)];
newYLim = [yl(1)-xyMargDataUnits(2), yl(2)+xyMargDataUnits(4)];
ax2 = axes('Units','Normalize','InnerPosition',[0 0 1 1]);
xline(xl(1),'b--', 'LineWidth', 1.5)
xline(xl(2),'b--', 'LineWidth', 1.5)
yline(yl(1),'b--', 'LineWidth',1.5)
yline(yl(2),'b--', 'LineWidth',1.5)
text(ax2,min(xlim(ax2)),max(ylim(ax2)),...
sprintf('xlim: [%.1f, %.1f]\nylim: [%.1f, %.1f]', ...
newXLim(1),newXLim(2),newYLim(1),newYLim(2)), ...
'VerticalAlignment','Top','HorizontalAlignment','Left',...
'FontSize', 12, 'FontWeight','bold','fontName','fixedwidth',...
The image below shows several iterations of this demo.
Best Answer