Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the subplot sizes unchanged after putting a colorbar

Tags:

matlab

Let us say we have a 1-by-2 subplot and we plot some graphics inside as follows:

subplot(1,2,1)
surf(peaks(20))

subplot(1,2,2)
surf(peaks(20))

enter image description here

And then we want to put a colorbar:

colorbar

enter image description here

I don't want the right figure squezzed as in the result. How can we put the colorbar out of the rightmost figure in a row of subplots and keep the sizes of them unchanged?

Note: Actually, I need it for plotting images where the colorbar is common and I want to put it on the right. I used this toy example for simplicity.

like image 599
petrichor Avatar asked May 18 '12 08:05

petrichor


2 Answers

You could just extract the position of the first plot and use on the second. MATLAB automatically moves the colorbar to the right when rescaling.

f1=figure(1);clf;
s1=subplot(1,2,1);
surf(peaks(20));

s2=subplot(1,2,2);
surf(peaks(20));
hb = colorbar('location','eastoutside');

%% # Solution:
s1Pos = get(s1,'position');
s2Pos = get(s2,'position');
s2Pos(3:4) = [s1Pos(3:4)];
set(s2,'position',s2Pos);



%% # Alternative method. Brute force placement
set(s1,'Units','normalized', 'position', [0.1 0.2 0.3 0.6]);
set(s2,'Units','normalized', 'position', [0.5 0.2 0.3 0.6]);
set(hb,'Units','normalized', 'position', [0.9 0.2 0.05 0.6]);

enter image description here

like image 72
Vidar Avatar answered Oct 17 '22 08:10

Vidar


This is just what I was looking for. After implementing Vidar's automatic solution I came up with a simplification. Get the position of the far right axes BEFORE adding the colorbar, and then just reset the squeezed position to the original:

f1=figure(1);clf;
s1=subplot(1,2,1);
surf(peaks(20));

s2=subplot(1,2,2);
surf(peaks(20));
s2Pos = get(s2,'position');

hb = colorbar('location','eastoutside');
set(s2,'position',s2Pos);
like image 43
kkcc Avatar answered Oct 17 '22 08:10

kkcc