MATLAB: Avoid colorbar resizing image

axescolorbarimage resize

Hi guys –
How can I prevent an image from being resized when a colorbar is introduced? I am plotting two plots side by side, one with a line plot and one with imagesc. Before the colorbar is added the plots are exactly the same size, which I would prefer, but when I add the colorbar the imagesc plot is resized to be smaller than before. I'd like to avoid this.

Best Answer

Jason, just try this demo code and I think all your questions will be answered:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Put up a plot in the first position
h1 = subplot(1,2,1);
plot(rand(15), 'LineWidth', 3);
title('Line Plot', 'FontSize', fontSize);
% Get the current axis size

originalSize1 = get(gca, 'Position')
% Put up an image in the second position
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
grayImage = imread(fullFileName);
% Display the original gray scale image.
h2 = subplot(1, 2, 2);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]); % Maximize figure.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off');
% Get the current axis size
originalSize2 = get(gca, 'Position')
uiwait(msgbox('Click OK to see a colorbar and watch how it changes both axes sizes'));
colormap('winter');
colorbar;
title('Shrunken Image with ColorBar', 'FontSize', fontSize);
% Print out the new sizes and see how they are different.
newSize1 = get(h1, 'Position')
newSize2 = get(h2, 'Position')
uiwait(msgbox('Click OK to restore the original image size'));
% Reset axes to original size.
set(h1, 'Position', originalSize1); % Can also use gca instead of h1 if h1 is still active.
set(h2, 'Position', originalSize2); % Can also use gca instead of h2 if h2 is still active.
title('Restored Image with ColorBar', 'FontSize', fontSize);
% Print out the restored sizes to verify.
restoredSize1 = get(h1, 'Position')
restoredSize2 = get(h2, 'Position')