MATLAB R2022a and earlier:
Before MATLAB R2022b, the "TightInset" property of an axis could be used to acquire the margins around the axis which included all desired text labels. However, this property returns the margins in the form [left bottom right left], which refer to the distance from the axis position that the margins extend. To make use of this information, the position vector of the axis can be updated as seen below for an example axis:
ax = gca;
ax_pos = ax.Position;
ax_tight_inset = ax.TightInset;
ax_pos_tight(1:2) = ax_position(1:2) - ax_tight_inset(1:2);
ax_pos_tight(3:4) = (ax_position(1:2) + ax_position(3:4)) + ax_tight_inset(3:4) - ax_tight_inset(1:2);
where "ax_pos_tight" contains the new position vector.
MATLAB R2022b and later:
As of MATLAB R2022b, the "tightPosition" function was introduced. "ax_pos_tight" can be recreated using the "tightPosition" function, as seen below:
ax_pos_tight = tightPosition(ax, IncludeLabels=true);
Please refer to the following documentation page for more information: