Only one colorbar for subplots while plotting in a for loop.
20 次查看(过去 30 天)
显示 更早的评论
x = 1:10;
y = x';
z1 = repmat(x,10,1);
z(:,:,1)=z1;z(:,:,2)=z1;
% this only sets the mapping and colorbar
colorbarrange = [0 12]; % assumed to be integer values
levels = colorbarrange(1):colorbarrange(2);
maplength = diff(colorbarrange);
% plot things
fig1=figure(1);
for i=1:2
sph{i} = subplot(1,2,i,'Parent',fig1);
s=contourf(sph{i},x,y,z(:,:,i),...
levels,"ShowText", true);
c1 = colorbar;
colormap(parula(maplength))
clim(colorbarrange)
% if you really want to make sure every tick is labeled
xticks(gca,ceil(min(x(:))):floor(max(x(:))));
c1.Ticks = levels;
end
Now as you can see here there are two colorbar. I want only one colobar right to second subplot. I tried to put colorbar outside the for loop but it will not match with the contorf plots color scale.
0 个评论
采纳的回答
Adam Danz
2023-7-7
I recommend using tiledlayout instead of subplot. Tiledlayout has numerous benefits over subplot including easy placement of global colorbars.
x = 1:10;
y = x';
z1 = repmat(x,10,1);
z(:,:,1)=z1;z(:,:,2)=z1;
colorbarrange = [0 12];
levels = colorbarrange(1):colorbarrange(2);
maplength = diff(colorbarrange);
fig1=figure(1);
tcl = tiledlayout(1,2,'TileSpacing','compact'); % <-- define axes grid
for i=1:2
% sph{i} = subplot(1,2,i,'Parent',fig1); % <-- remove
sph{i} = nexttile(tcl); % <-- create axes
s=contourf(sph{i},x,y,z(:,:,i),...
levels,"ShowText", true);
% c1 = colorbar; % <-- remove
colormap(parula(maplength))
clim(colorbarrange)
xticks(gca,ceil(min(x(:))):floor(max(x(:))));
c1.Ticks = levels;
end
% Add colorbar to the east of the layout
cb = colorbar(sph{i});
cb.Layout.Tile = 'east';
0 个评论
更多回答(1 个)
sushma swaraj
2023-7-7
Hi,
To have a single colorbar positioned to the right of the second subplot and match its color scale with the contour plots, you can make the following modifications to your code :
x = 1:10;
y = x';
z1 = repmat(x, 10, 1);
z(:,:,1) = z1;
z(:,:,2) = z1;
colorbarrange = [0 12]; % assumed to be integer values
levels = colorbarrange(1):colorbarrange(2);
maplength = diff(colorbarrange);
fig1 = figure(1);
sph = gobjects(2, 1); % Create an array to store subplot handles
for i = 1:2
sph(i) = subplot(1, 2, i, 'Parent', fig1);
contourf(x, y, z(:,:,i), levels, "ShowText", true);
colormap(parula(maplength))
clim(colorbarrange)
xticks(ceil(min(x(:))):floor(max(x(:))));
end
% Position the colorbar to the right of the second subplot
c1 = colorbar('Position', [0.92 0.1 0.02 0.8], 'Parent', fig1);
c1.Ticks = levels;

Hope it helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Colormaps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!