问题
I would like to make the following MATLAB plot have a single colorbar that extends along both subplots.
Something like this (done manually with the figure editor):
Note: This is different from the question asked here.
Thanks!
回答1:
I finally figured out a solution. The colorbar can be manually positioned in code but I wanted to keep everything the original spacing. My final solution is outlined below.
Step 1. Create the plot with a single colorbar on the bottom subplot.
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. Save the position vectors of the two subplots and the colorbar.
pos1 = ax(1).Position; % Position vector = [x y width height]
pos2 = ax(2).Position;
pos3 = cbar.Position;
Step 3. Update the position of the colorbar to extend to the top of the top subplot.
cbar.Position = [pos3(1:3) (pos1(2)-pos3(2))+pos1(4)];
Step 4. Update the width of the top subplot to accommodate the colorbar.
ax(1).Position = [pos1(1) pos1(2) pos2(3) pos1(4)];
Step 5. Update the width of the bottom subplot to accommodate the colorbar.
ax(2).Position = pos2;
Wait, I thought the bottom subplot already accommodated the colorbar? Actually, when setting the position of the colorbar manually (step 3), the corresponding axis no longer scales accordingly. From the documentation:
If you specify the Position property, then MATLAB changes the Location property to 'manual'. The associated axes does not resize to accommodate the colorbar when the Location property is 'manual'.
The final result:
来源:https://stackoverflow.com/questions/54740163/single-colorbar-for-vertical-subplots