linearly map values with colormap matlab

57 views (last 30 days)
Md Shahriar Mahbub
Md Shahriar Mahbub on 30 Mar 2015
Edited: Stephen23 on 2 Apr 2015
I have a matrix (200x4) where first 3 values is used as X, Y and Z. I want display 4th value using different colors. The 4th column contains values from 0.0 to 1.0 (200 values). I want to map these value with colormap manually and linearly. smallest value should have blue color and largest value may have red color. I know that it is possible with scatter3. But I want to do using stem3 where I can specify the color manually from colormap.
How can I do that easily. Thanks in advance.
Regards,
Shaikat

Answers (2)

Debarati Banerjee
Debarati Banerjee on 2 Apr 2015
Try the sample code that I have provided below. It seems to be doing what you mentioned.
x=rand(20,1); %data to be plotted
ran=range(x); %finding range of data
min_val=min(x);%finding maximum value of data
max_val=max(x)%finding minimum value of data
y=floor(((x-min_val)/ran)*63)+1;
col=zeros(20,3)
p=colormap
for i=1:20
a=y(i);
col(i,:)=p(a,:);
stem3(i,i,x(i),'Color',col(i,:))
hold on
end
  1 Comment
Stephen23
Stephen23 on 2 Apr 2015
Note that you should not use i or j as variable names, as these are both names of the inbuilt imaginary unit.

Sign in to comment.


Stephen23
Stephen23 on 2 Apr 2015
Edited: Stephen23 on 2 Apr 2015
You can easily generate a colormap of any length directly from its function:
>> cool(5)
ans =
0 1.0000 1.0000
0.2500 0.7500 1.0000
0.5000 0.5000 1.0000
0.7500 0.2500 1.0000
1.0000 0 1.0000
So you can easily get all 200 colors too:
>> cool(200)
ans =
0 1.0000 1.0000
0.0050 0.9950 1.0000
0.0101 0.9899 1.0000
0.0151 0.9849 1.0000
0.0201 0.9799 1.0000
...
0.9799 0.0201 1.0000
0.9849 0.0151 1.0000
0.9899 0.0101 1.0000
0.9950 0.0050 1.0000
1.0000 0 1.0000
You can use this by specifying optional argument for stem3:
map = cool(200);
for k = 1:200
stem3(X,Y,Z, 'Color',map(k,:))
hold on
end
Although I used the colormap cool in these examples, this will work for any colormap function, so you can simply pick the best colormap for your application. You can view a list of all inbuilt colormaps in the colormap documentation, or you can find many excellent colormaps on MATLAB File Exchange too.
Note that different MATLAB versions use different default colormaps, so you will likely have to specify this colormap anyway. Older version use jet, newer version use parula as the default colormap.
Of course most plotting functions will use the current colormap anyway, without you needing to supply the colors. Read the colormap documentation to know how, or look at the examples for this FEX submission:
You might like the ColorBrewer colormaps too!

Categories

Find more on Colormaps 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!