Reputation: 99
I have a matrix M of integers (1, 2 or 3). I'd like to represent it with a heatmap and associate a fixed color to 1, 2 and 3. I use this piece of code :
map = [1, 1, 0; % color for 1 (yellow)
1, 0.5, 0 ; % color for 2 (orange)
0, 1, 0.5]; % color for 3 (green)
HeatMap(M,'Colormap',map,'Symmetric','false');
When M contains at least one 1, one 2 and one 3, there isn't any problem. But when M contains only 3s for example, the heatmap isn't as I want (all green). How can I solve this problem?
Upvotes: 5
Views: 1373
Reputation: 25242
The easiest would be not to use HeatMap
which is a quite inconvenient function based on Java.
Rather use imagesc
or pcolor
where you can easily fix the color axis with caxis
:
map = [1, 1, 0; % color for 1 (yellow)
1, 0.5, 0 ; % color for 2 (orange)
0, 1, 0.5]; % color for 3 (green)
%// left plot
subplot(131)
M = randi(3,3,3);
imagesc(M)
colormap(map)
caxis( [1 3] )
%// right plot
subplot(132)
M = 3*ones(3);
imagesc(M)
colormap(map)
caxis( [1 3] )
%// legend
subplot(133)
set(gca,'visible','off')
c = colorbar
caxis( [1 3] )
c.Ticks = [1.25,2,2.75]
c.TickLabels = 1:3
Upvotes: 3
Reputation: 35525
It doesn't look like you can do this easily.
In Matlab 2013b or older (I haven't tried in 2014b) when you call HeatMap
it internally goes through a process of creating axes and settin the colors and so on. Eventually it gets to a point inside plot.m
where the following function is called:
function scaleHeatMap(hHMAxes, obj)
%SCALEHEATMAP Update the CLIM in image axes
if obj.Symmetric
maxval = min(max(abs(obj.Data(:))), obj.DisplayRange);
minval = -maxval;
else
maxval = min(max(obj.Data(:)), obj.DisplayRange);
minval = min(obj.Data(:));
end
set(hHMAxes, 'Clim', [minval,maxval]);
end
This function does actually define the limits of the colormap using the axes of the heatmap (hHMAxes
), but that object is not returned by the HeatMap()
call, unfortunately.
The only ways I can think of getting out of this problem are:
plot.m
function. This is generally a quite bad idea.myHeatMap
function, that does everything the original one does but with a changed functionality on the Clim
property on the axes.HeatMap
at all and create an equally looking plot using e.g. surf
or imshow
.if
statement before the call of HeatMap
, and check if there is a single value in the colormap (numel(unique(M(:)))==1
), and if that happens, change your map
to a single valued colormap, with the color of your choice.The easiest one is by far 4.
Upvotes: 3