MATLAB Answers

Program the colormap of a graph using different colors for different ranges

3 views (last 30 days)
Sébastien MAILFERT
Sébastien MAILFERT on 6 Jul 2016
Edited: Guillaume on 6 Jul 2016
Dear all,
I have a matrix containing NaNs and numbers:
x=[NaN 1.2 68.65 155.8 2.41 1.81 .2;
4.41 NaN 45.19 127.2 6.26 72.73 1.6;
35.39 28.59 NaN 37.36 94.5 4.87 48.62;
78.4 93.64 4.64 NaN 181.99 17.14 128.6;
8.35 29.8 9.23 151.1 NaN 128.6 1.7;
53.43 55.42 8.71 14.93 117.62 NaN 74.61;
.7 1.12 21.95 56.4 13.43 35.88 NaN];
Now, I would like to create an image with a colorbar where the colors change according to specific ranges:
  • NaN -> [255 255 255]
  • 0 < x < 0.001 -> [197 215 232]
  • 0.001<x<0.01 -> [132 170 206]
  • 0.01<x<0.1 -> [89 141 202]
  • 0.1<x<3.8 -> [0 0 255]
  • x>3.8 -> [255 0 0]
What I did is this code:
Results_Sorted=sort(x(:)); % sort data
map=zeros(size(Results_Sorted,1),3,'double');% create the colormap
%looking for indexes of value ranges
pos_0p001_min= sum(Results_Sorted<=0.001);
pos_0p01_min=sum(Results_Sorted<=0.01);
pos_0p1_min=sum(Results_Sorted<=0.1);
pos_1_min=sum(Results_Sorted<=1);
pos_3p8_min=sum(Results_Sorted<=3.8);
% fill the map with my colors
for i=1:pos_0p001_min
map(i,:,:)=[255 255 255];
end%for
for i=pos_0p001_min+1:pos_0p01_min+1
map(i,:,:)=[197 215 232];
end%for
for i=pos_0p01_min+1:pos_0p1_min+1
map(i,:,:)=[132 170 206];
end%for
for i=pos_0p1_min+1:pos_1_min+1
map(i,:,:)=[89 141 202];
end%for
for i=pos_1_min+1:pos_3p8_min+1
map(i,:,:)=[0 0 255];
end%for
for i=pos_3p8_min+1:size(map,1)
map(i,:,:)=[255 0 0];
end%for
map=map/255;
imagesc(Result);
colorbar;
colormap(map);
But this is not exactly what I need... Could you help me to understand where is my error? Best regards. Sébastien

  0 Comments

Sign in to comment.

Answers (1)

Guillaume
Guillaume on 6 Jul 2016
Edited: Guillaume on 6 Jul 2016
My suggestion would be to inverse the problem: Have a simple colour map with just your six entries and discretise your x so that it's only got six different values. You can adjust the colourbar ticks so that it displays the real x values instead of the discretised values:
map = [255 255 255
197 215 232
132 170 206
89 141 202
0 0 255
255 0 0] / 255;
fakex = discretize(x, [0 0.001 0.01 0.1 3.8 Inf]) + 1; %+1 since NaN is the first colour
fakex(isnan(x)) = 1;
imagesc(fakex); %note that your example x is not very good since it only includes the last 2 intervals
colormap(map);
hbar = colorbar;
%option 1: label start and end of each colour box
hbar.Ticks = linspace(1, 6, 7);
hbar.TickLabels = {'NaN', '0', '0.0001', '0.01', '0.1', '3.8', 'Inf'}
%option 2: label middle of each colour box
hbar.Ticks = conv(linspace(1, 6, 7), [0.5 0.5], 'valid');
hbar.TickLabels = {'NaN', '0 - 0.0001', '0.0001 - 0.01' '0.01 - 0.1', '0.1 3.8', '3.8 - Inf'}

  0 Comments

Sign in to comment.