Only one colorbar for subplots while plotting in a for loop.
18 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Adam Danz
il 7 Lug 2023
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 Commenti
Più risposte (1)
sushma swaraj
il 7 Lug 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!
0 Commenti
Vedere anche
Categorie
Scopri di più su Colormaps in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!