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

1

12

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)

Topee answered 10/3, 2011 at 12:53 Comment(0)
F
16

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

Fellows answered 10/3, 2011 at 14:28 Comment(2)
+1 thanks. Too bad the width is stored in the position array so one can't use linkprop to make sure the plot doesn't become weird when hiding the colorbar again...Topee
if you want to keep the aspect ratio of the image (e.g., using imshow) this solution will not work... You'll need to use imagesc instead.Contemptuous

© 2022 - 2024 — McMap. All rights reserved.