MATLAB: How to add one colorbar for the whole figure with tiled layout

colorbartiled layout

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

Best Answer

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 can be assigned to just one of the subplots or it can be a global colorbar assigned to the tiledlayout object.
Here's a demo.
tlo = tiledlayout(2,1)
tlo =
TiledChartLayout with properties: TileArrangement: 'fixed' GridSize: [2 1] Padding: 'loose' TileSpacing: 'loose' Show all properties
% Top plot
h(1) = nexttile(tlo); % Get axis handle
surf(h(1), peaks)
% Bottom plot
h(2) = nexttile(tlo); % Get 2nd axis handle
surf(h(2), peaks * 2.5)
% Set colormap and color limits for all subplots
set(h, 'Colormap', jet, 'CLim', [-20 20])
% assign color bar to one tile
cbh = colorbar(h(end));
% To position the colorbar as a global colorbar representing
% all tiles,
cbh.Layout.Tile = 'east';
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))
Related Question