[HEATMAP] Display single colorbar for a multiplot

35 次查看(过去 30 天)
As in the title, I need help displaying a single colorbar for several subplots of HEATMAPS.
I tried both with subplots, and tiled design, but none works.
Please, I need help with heatmaps: before people start saying "duplicate", I would like to point out that the methods for countours() and surf() DO NOT WORK with heatmap().
Thanks for the help
E.
  3 个评论
Giovanni Bambini
Giovanni Bambini 2023-8-28
yes. That refers to conturf. With heatmap I get a Matlab error
Dyuman Joshi
Dyuman Joshi 2023-8-28
It is notoriously hard to work with heatmap and their colorbars.
The only way I could find to make it work is if the layout for subplot/tiledlayout is horizontal.

请先登录,再进行评论。

采纳的回答

Adam Danz
Adam Danz 2023-8-28
编辑:Adam Danz 2023-8-28
Here's a demo showing the following steps needed to create a figure with multiple heatmaps that share the same global colorbar. Since a colorbar cannot be assigned to a heatmap, an invisible axes is created to host the colorbar.
  1. Create the heatmaps within a tiledlayout. Turn off colorbar visibility.
  2. Compute the global color limits which is the [min,max] range of color limits between all heatmaps.
  3. Set the color limits for each heatmap to the global limits since the heatmaps will all share the same colorbar
  4. Create an invisible axes that uses the same colormap as the first heatmap and the same color limits as the global color limits.
Note that this approach does not use the same type of colorbar as heatmap. The missing values indicator in heatmap's colorbar will not appear using this approach.
rng('default')
fig = figure();
tcl = tiledlayout(fig,2,2);
n = 4; % number of heatmaps
h = gobjects(n,1);
for i = 1:n
ax = nexttile(tcl);
h(i) = heatmap(rand(5)*randi(5),'ColorbarVisible','off');
end
% Equate color limits in all heatmaps
colorLims = vertcat(h.ColorLimits);
globalColorLim = [min(colorLims(:,1)), max(colorLims(:,2))];
set(h, 'ColorLimits', globalColorLim)
% Create global colorbar that uses the global color limits
ax = axes(tcl,'visible','off','Colormap',h(1).Colormap,'CLim',globalColorLim);
cb = colorbar(ax);
cb.Layout.Tile = 'East';
  2 个评论
Giovanni Bambini
Giovanni Bambini 2023-8-29
I did not understand the note you wrote.
In my case everything is working, thanks for the help, you were super useful and clear.
Adam Danz
Adam Danz 2023-8-29
Thanks @Giovanni Bambini. Heatmap's colorbar has a special feature when there are missing values in the heatmap data. It indicates missing values in a small box under the colorbar. My solution above creates a regular colorbar which will not have this feature.
Here's a demo
data = magic(5);
data([1 5 20]) = NaN;
heatmap(data)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by