MATLAB Answers

how to add one colorbar for the whole figure with tiled layout?

268 views (last 30 days)
Jing Ci Neo
Jing Ci Neo on 22 Dec 2019
Commented: Jing Ci Neo on 22 Dec 2019
The matlab example shows that we can add colorbar to individual tiles see attached, but can we add one colorbar for the whole figure? I also have problems with adding a legend and positioning it.
Example code:
tiledlayout(2,1)
% Top plot
nexttile
surf(peaks)
colorbar
% Bottom plot
nexttile
mesh(peaks)
colorbar

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 22 Dec 2019
To use one colorbar that represents the color values for each subplot, each subplot must use the same colormap and the same colorscale. The colorbar should be assigned to just one of the subplots.
Here's a demo.
tiledlayout(2,1)
% Top plot
h(1) = nexttile(); % Get axis handle
surf(peaks)
% Bottom plot
h(2) = nexttile; % Get 2nd axis handle
surf(peaks * 2.5)
% Set colormap and color limits for all subplots
set(h, 'Colormap', jet, 'CLim', [-20 20])
% assign color bar to last subplot (you can select any subplot)
cbh = colorbar(h(2));
If the subplots were produced using subplot(), you can reposition the colorbar so that it is not associated with just one subplot. This example places the subplot the right of the figure, centered vertically.
% Reposition to figure's left edge, centered vertically
cbh.Position(1) = .95-cbh.Position(3);
cbh.Position(2) = 0.5-cbh.Position(4)/2;
% decrease horizontal extent of subplots to 92% of their current width
set(h, {'Position'}, mat2cell(vertcat(h.Position) .* [1 1 .92, 1], ones(size(h(:))),4))

  3 Comments

Jing Ci Neo
Jing Ci Neo on 22 Dec 2019
It worked, thanks! I have another question regarding a sidebar function, cbarrow. Using cbarrow with tiled layout doesn't work at all, it erases the colorbar (see attached). Do you have any idea why that is happening?
Code
colormap(redblue)
h=colorbar('westoutside');
cbarrow
Adam Danz
Adam Danz on 22 Dec 2019
This is a limitation with tiledlayout/nexttile method. This method has a lot more restrictions than the simpler approach, using subplot().
% tiledlayout(2,1) % remove this
h(1) = subplot(2,1,1); % use subplot
surf(peaks)
% Bottom plot
h(2) = (subplot(2,1,1)) % use subplot
surf(peaks * 2.5)
now you can use the cbarrow() function.

Sign in to comment.

More Answers (0)

Sign in to answer this question.