Only one colorbar for subplots while plotting in a for loop.
Show older comments
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.
Accepted Answer
More Answers (1)
sushma swaraj
on 7 Jul 2023
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!
Categories
Find more on Color and Styling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
