MATLAB: Save plot with minimal white space without removing part of the figure

plot

In order to save MATLAB plots with minimal white space I have been using the code from this resource,with the code copied below.
ax = gca;
outerpos = ax.OuterPosition;
ti = ax.TightInset;
left = outerpos(1) + ti(1);
bottom = outerpos(2) + ti(2);
ax_width = outerpos(3) - ti(1) - ti(3);
ax_height = outerpos(4) - ti(2) - ti(4);
ax.Position = [left bottom ax_width ax_height];
However, part of the figure is now cut off (the 0 on the axis bar). Is there a simple solution to this problem?
Edit: also there is still white space at the left and right edges. It is hard to see extra white space so I also attached the image. Of course I can remove this manually, but since I am processing many images it would be much faster to do it automatically.
Thanks!

Best Answer

Follow this demo to maximize an axis with equal aspect ratio and a colorbar within a figure.
% Set up figure size before moving forward.
% Figure units must be pixels (default).
fh = figure('Units','Pixels');
% Set axes is fill figure
ax = axes('position',[0 0 1 1]);
% create sample data
x = -10:10;
y = -10:10;
[X,Y] = meshgrid(x,y);
Z = X.^2 + Y.^2;
% plot
contourf(ax,X,Y,Z); % Use axis handle!

cbh = colorbar(ax); % Use axis handle!
cbh.Position([2,4]) = [.015,.97]; % decrease vertical size of colorbar
set(ax,'xtick',[])
set(ax,'ytick',[])
axis(ax,'equal')
% Set colorbar units and axis units to match figure units
cbh.Units = fh.Units;
ax.Units = fh.Units;
% Move axis all the way to the left
ax.Position(1) = -(ax.Position(3)-ax.Position(4))/2 + 1;
% Move colorbar to the left (the +5 at the end is pixel space between plot and colorbar)
cbh.Position(1) = sum(ax.Position([1,3])) + ax.Position(1) + 5;
% Now shrink the width of the figure; the *1.5 at the end is to factor in the y tick marks on the colorbar.
fh.Position(3) = sum(cbh.Position([1,3]))+cbh.Position(3)*1.5;
% Turn off figure border (if that's what you want to do)
fh.MenuBar = 'none';
fh.ToolBar = 'none';
190617 130015-Figure 1.jpg