フィルターのクリア

Only one colorbar for subplots while plotting in a for loop.

19 ビュー (過去 30 日間)
Ankitkumar Patel
Ankitkumar Patel 2023 年 7 月 7 日
回答済み: Adam Danz 2023 年 7 月 7 日
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.

採用された回答

Adam Danz
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';

その他の回答 (1 件)

sushma swaraj
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!

カテゴリ

Help Center および File ExchangeColormaps についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by