How to map a specific value into RGB-color code in

2019-01-29 02:47发布

问题:

This question already has an answer here:

  • How to create a custom colormap programmatically? 2 answers

I'm doing data-analysis in Matlab and I have data points from three different classes: (no-damage, small damage, and high damage). These classes are represented by integer values (1, 2, 3).

I'm predicting these classes by using regularized linear regression and I want to create a picture, where I have the data points highlighted with the colors: 1 = green, 2 = yellow, 3 = red. This is no problem to me, but what I would also like to is to create a secondary picture, where I have predicted these classes with my regression model. The problem is that my regression model doesn't give integer values but real values (I could overcome this by rounding the values to nearest integer, but I don't want to ;) )

What I would like to do is: map the real value (say 1.45) into a RGB-code, which would correspond to a color in the range green -- yellow -- red.

Let me give an example:

If the prediction value of my model is 1.45, then the corresponding color code would fall between green -- yellow.

If my prediction value is 2.5, then the color code would fall between yellow -- red.

So the closer the value is to 1, the closer the color code is to green, the closer the value is to 2, the closer the color code is to yellow and the closer the value is to 3, the closer the color code is to red.

I would only like to colors like greeb, yellow, orange, red in my prediction picture =)

Hope my question is clear =) Any good ideas? =)

Please let me know if my question is unclear =)

回答1:

You can create your own colormap easily, you just need to define a Nx3 matrix with your colors. Let me show you an example code with the map you proposed.

clear;clc;

% Prepare example data rage 1-3
Z=peaks;
Z=peaks./max(Z(:));
Z=(Z+1)*3/2;

%Define colormap
c1=[0 1 0]; %G
c2=[1 1 0]; %Y
c3=[1 0 0]; %R
n1=20;
n2=20;
cmap=[linspace(c1(1),c2(1),n1);linspace(c1(2),c2(2),n1);linspace(c1(3),c2(3),n1)];
cmap(:,end+1:end+n2)=[linspace(c2(1),c3(1),n2);linspace(c2(2),c3(2),n2);linspace(c2(3),c3(3),n2)];
colormap(cmap')

%Plot
surf(Z)
colorbar
caxis([1 3]) 

Result: (NOTE, you may want to add more n2 values so the red is more noticeable.