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

假装没事ソ 提交于 2019-12-03 08:20:00

问题


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,:));

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)


回答1:


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)



来源:https://stackoverflow.com/questions/5259853/matlab-how-to-align-the-axes-of-subplots-when-one-of-them-contains-a-colorbar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!