我终于找到了解决办法。颜色条可以在代码中手动定位,但我想保持所有内容的原始间距。我的最终解决方案概述如下。
Step 1.在底部子图上创建带有单个颜色条的图。
figure('color', 'white', 'DefaultAxesFontSize', fontSize, 'pos', posVec)
ax(1) = subplot2(2,1,1);
pcolor(x2d, t2d, dataMat1)
shading interp
ylim([0 10])
xlim([-0.3 0.3])
xticklabels({})
set(gca, 'clim', [-20 0])
colormap(flipud(gray))
set(gca,'layer','top')
axis ij
ax(2) = subplot2(2,1,2);
pcolor(x2d, t2d, dataMat2);
xlabel('x')
ylabel('y')
shading interp
ylim([0 10])
xlim([-0.3 0.3])
set(gca, 'clim', [-20 0])
yticklabels({})
cbar = colorbar;
cbar.Label.String = 'Normalized Unit';
colormap(flipud(gray))
set(gca,'layer','top')
axis ij
Step 2.保存两个子图和颜色条的位置向量。
pos1 = ax(1).Position; % Position vector = [x y width height]
pos2 = ax(2).Position;
pos3 = cbar.Position;
Step 3.更新颜色条的位置以延伸到顶部子图的顶部。
cbar.Position = [pos3(1:3) (pos1(2)-pos3(2))+pos1(4)];
Step 4.更新顶部子图的宽度以容纳颜色条。
ax(1).Position = [pos1(1) pos1(2) pos2(3) pos1(4)];
Step 5.更新底部子图的宽度以容纳颜色条。
ax(2).Position = pos2;
等等,我以为底部的子图已经容纳了颜色条?实际上,当手动设置颜色条的位置时(步骤3),相应的轴不再相应缩放。来自文档 https://www.mathworks.com/help/matlab/ref/matlab.graphics.illustration.colorbar-properties.html:
如果您指定 Position 属性,MATLAB 会将 Location 属性更改为“手动”。当“位置”属性为“手动”时,关联的轴不会调整大小以适应颜色条。
最终结果: