How to use Position property to make axes height tight to figure height
16 views (last 30 days)
Show older comments
Hello,
I am trying create plots with a specific figure height and minimal whitespace, but I seem to be misunderstanding how to use the position properties because I am not getting what I expect. I've reduced my issue to the code below:
close all; clear; clc
plot([0,1],[1,2])
fig_height = 800;
axis square
ax = gca;
fig = gcf;
fig.Position(1:2) = [1000,100];
fig.Position(4) = fig_height;
% Fit axes height to figure height
ax.Position(4) = 1 - ax.TightInset(2) - ax.TightInset(4);
% Fit figure width to axes width
fig_width = ax.Position(3) + ax.TightInset(1) + ax.TightInset(3);
fig.Position(3) = fig_width;
% Readjust axes position within figure
ax.Position(1) = ax.TightInset(1);
ax.Position(2) = ax.TightInset(2);
At the line below I expect the axes to grow to the height of the figure so I can subsequently change the figure width to match the axes plus tightinset widths, but for larger figures it doesn't grow, it just rises vertically in the figure.
ax.Position(4) = 1 - ax.TightInset(2) - ax.TightInset(4);
I also must have a misunderstanding of TightInset because sometimes some TightInset elements are zero even when I have xlabels, ylabels, titles, and exterior legends. I had thought that the axes position refers to the plot area (no ticks, labels, titles etc.), while the TightInset regards the widths and heights of the tick labels, axes labels, titles etc., but this must not be an accurate understanding.
I've done a lot of troubleshooting, but can't seem to figure this one out. Any help would be greatly appreciated.
Thank you.
1 Comment
Richard
on 16 Sep 2020
Hello Jacob,
I had similar problem; for some reason, when you try to do the same operation as you do with y axis ( ), for x axis, it doesnt retrive the exact number from ax.TightInset. I was trying to figure it out, and here is my solution:
fig=figure;
ax=gca;
x=linspace(1,10,10);
y=rand(10,1);
plot(x,y);
xlabel('My x label');
ylabel('My y label');
set(fig,'Position',[80 80 1200 450]);
newdim=[ax.TightInset(1),...
ax.TightInset(2),...
1-ax.TightInset(3)-ax.TightInset(1)*1.05,...
1-ax.TightInset(4)-ax.TightInset(2)*1.05];
set(ax,'Position',newdim);
Now, all you need to specify its 'position' property of figure, and the margins will adjust. It has 5% extra space from right and upper side of figure, so it fits nicely in figure. I hope it will help.
RD
Answers (0)
See Also
Categories
Find more on Color and Styling 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!