필터 지우기
필터 지우기

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

조회 수: 18 (최근 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 CenterFile Exchange에서 Colormaps에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by