Adding a legend when using imagesc, including whit

2019-02-28 12:57发布

I have a 35x43 matrix of data with vales ranging from 1-6 and lots of NaNs.

I want to NaNs to be white, and the numbers to each be a different colour. I need a legend with the 6 different colour and labels on it.

I can achieve most of this with the following code, however the colours in the legend do not match the colours in the figure. See code below

    figure(6)
subplot(1,2,1)
imagesc(lut)
title('Highest Weighted Predictor variable for each Pixel')
ylabel('Longitude')
xlabel('Latitude')
caxis([0, 7])
myColorMap = jet(7);
myColorMap(1,:) = 1;
colormap(myColorMap);
M = jet(7); % Notice the 3, here and below
hold on
L = line(ones(7),ones(7));
set(L,{'color'},mat2cell(M,ones(1,7),3))
[legh,objh,outh,outm] = legend('First','Second','Location','Southeast');
set(objh,'linewidth',200);
legend('Forest','Shrubland','Savanna','Grassland','Agricultural','Barron');
grid on
ax = gca
ax.GridAlpha = .2
ax.XTick = [5 10 15 20 25 30 35 40];
ax.YTick = [5 10 15 20 25 30];
ax.XTickLabel = {'118^{o}E','123^{o}E','128^{o}E', '133^{o}E', '138^{o}E', '143^{o}E','148^{o}E', '153^{o}E'};
ax.YTickLabel = {'13^{o}S','18^{o}S','23^{o}S','28^{o}S','33^{o}S','38^{o}S'};
ax.TickLength =[0.0 0.0]

2条回答
\"骚年 ilove
2楼-- · 2019-02-28 13:21

To display the NaN values as white I would use something like this. Then for your colormap, just use jet(6). Then the colors will match up just fine.

lut = [1:6 NaN];

myColorMap = jet(6);

imagesc(lut, 'AlphaData', ~isnan(lut))
colormap(myColorMap);

L = line(ones(6), ones(6));
set(L, {'Color'}, num2cell(myColorMap, 2))

legend(L, {'Forest','Shrubland','Savanna','Grassland','Agricultural','Barron'})

enter image description here

查看更多
forever°为你锁心
3楼-- · 2019-02-28 13:28

I would suggest an alternative solution using a colorbar with individual ticks:

%// example data
lut = randi(6,35,43);
lut(1:23:end) = NaN;

%// parts of your your code
figure(6)
% subplot(1,2,1)
imagesc(lut)
title('Highest Weighted Predictor variable for each Pixel')
ylabel('Longitude')
xlabel('Latitude')
caxis([0, 7])
myColorMap = jet(7);
myColorMap(1,:) = 1;
colormap(myColorMap);
M = jet(7); % Notice the 3, here and below
hold on

%// colorbar
c = colorbar
c.Ticks = (1:6)+0.5
c.TickLabels = {'Forest','Shrubland','Savanna','Grassland','Agricultural','Barron'}

enter image description here

查看更多
登录 后发表回答