Separate categories in heatmap colorscale
7 views (last 30 days)
Show older comments
Hello,
I am using a lot heatmaps to illustrate matrices of data such as this one. I often run in the scenario where I could use a data value that would appear similar to NaN but in another color. Here I gave the tiles the value -10 and troncated the colorscale, but I was wondering if anyone knows of a cleaner way to do it because this method is not always optimal.

Thanks !
0 Comments
Accepted Answer
Voss
on 5 Sep 2023
Edited: Voss
on 5 Sep 2023
One way would be to put a patch object over the particular cells of the heatmap that you want to be different. Here's a way to do that:
% first, a matrix with some NaN elements:
M = magic(10);
M([1 2 3 11 12 21]) = NaN;
% create the heatmap:
h = heatmap(M);
% color to use to obscure some particular cells of the heatmap:
color = 'w';
% let's say these are the linear indices of the elements in M you
% would replace with -10 (or whatever special value) and color with
% the specified color (I just picked some locations in the lower-
% right of the heatmap):
idx = [70 79 80 86 89 90 95 96 97 98 99 100];
disp(idx(:));
% convert those linear indices to rows and columns:
[m,n] = size(M);
[ridx,cidx] = ind2sub([m,n],idx);
disp([ridx(:),cidx(:)]);
% you can't put a patch into a heatmap chart, so create a new invisible
% axes on top of the heatmap, with the same size, limits, and
% orientation (YDir) as the heatmap:
ax = axes('Units','normalized','Position',h.InnerPosition, ...
'Visible','off','XLim',[0.5 n+0.5],'YLim',[0.5 m+0.5],'YDir','reverse');
% put a patch in the new axes, to obscure those particular cells in the
% heatmap, using the specified color:
xd = 1:n;
yd = 1:m;
patch(ax,xd(cidx)+[0;0;1;1]-0.5,yd(ridx)+[0;1;1;0]-0.5,color)
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!