Matlab: How to align the axes of subplots when one of them contains a colorbar?

Tobias Kienzler picture Tobias Kienzler · Mar 10, 2011 · Viewed 15.3k times · Source

Minimal example:

[x,y,z] = peaks(50);
figure;
subplot(5,1,1:4);
pcolor(x,y,z);
shading flat;
colorbar;
subplot(5,1,5);
plot(x(end/2,:), z(end/2,:));

output

In this example I'd like to have the lower subplot show the cross-section of peaks along y=0 and the plot ending at the same position as the pcolor subplot, so that the x ticks are on identical positions. In fact, I don't need the duplicate x axis then. So,

How to rescale the lower subplot such that the right limit matches the right limit of the upper one's plot part? (preferably such that the colorbar can be switched on/off without destroying that alignment)

(FYI I learned I can use the linkaxes command then to have a correct zoom behaviour in a second step)

Answer

Jonas picture Jonas · Mar 10, 2011

You can just set the width of the second subplot to the width of the first by changing the Position property.

[x,y,z] = peaks(50);
figure;
ah1 = subplot(5,1,1:4); %# capture handle of first axes
pcolor(x,y,z);
shading flat;
colorbar;
ah2 = subplot(5,1,5); %# capture handle of second axes
plot(x(end/2,:), z(end/2,:));

%# find current position [x,y,width,height]
pos2 = get(ah2,'Position');
pos1 = get(ah1,'Position');

%# set width of second axes equal to first
pos2(3) = pos1(3);
set(ah2,'Position',pos2)

You can then further manipulate your axes properties, for example you can turn of the x-labels on the first plot, and move the second one up so that they touch:

set(ah1,'XTickLabel','')
pos2(2) = pos1(2) - pos2(4);
set(ah2,'Position',pos2)

enter image description here