How to tight-fit axis position to include text labels?

I want to store the position vector ([left bottom width height]) of my axis including the text labels (i.e., title, axis labels, tick labels). How can I do that?

 Accepted Answer

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; % Get axis
ax_pos = ax.Position;
ax_tight_inset = ax.TightInset;
ax_pos_tight(1:2) = ax_position(1:2) - ax_tight_inset(1:2); % Update left and bottom
ax_pos_tight(3:4) = (ax_position(1:2) + ax_position(3:4)) + ax_tight_inset(3:4) - ax_tight_inset(1:2); % Update width and height
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: 

More Answers (0)

Categories

Products

Release

R2022b

Community Treasure Hunt

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

Start Hunting!