How do I associate specific colors with specific numbers of a matrix?
94 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ivan Verstraeten
am 12 Aug. 2019
Kommentiert: Adam Danz
am 13 Aug. 2019
Title basically says it all; I want to be able to control which color get associated with which number. I have tried the code stated below to give a color to every number from 0 to 5. The way I thought this code would work was that the first row of cmap would be the color for 0, the second for 1, the third for 2, etc. But it still seems to associate colors from cmap randomly to the numbers in the matrix A.
A=[1:3;2:4;3:5;0 0 0];
cmap = [0 0.5 0.5;0.75 0.75 0;1 0.75 0.25;
0.25 0 1;1 1 0.75;0.75 0 0.75;
0.75 0.75 0;0.25 0.25 0.25;1 0.5 0];
colormap(cmap);
caxis([0 5]);
imagesc(A);
Thanks for reading!
0 Kommentare
Akzeptierte Antwort
Adam Danz
am 12 Aug. 2019
Bearbeitet: Adam Danz
am 13 Aug. 2019
You set 9 colors in your colormap but you only have 6 unique intergers in "A". That means you're asking matlab to distribute 9 colors evenly across 6 values. To make see the mapping, add a colorbar to your plot and set the y axis ticks of the colorbar to intergers (see below).
cb = colorbar();
set(cb,'YTick', 1:9)
If you want a 1:1 mapping you've got 2 opitions.
Option 1: number of colors = range of values
You've got 6 unique integer values (see below) then you must have only 6 colors in your colormap.
unique(A(:))
ans =
0
1
2
3
4
5
Here's your code with only the first 6 colors and with a colorbar.
A=[1:3;2:4;3:5;0 0 0];
cmap = [0 0.5 0.5;
0.75 0.75 0;
1 0.75 0.25;
0.25 0 1;
1 1 0.75;
0.75 0 0.75];
colormap(cmap);
imagesc(A);
cb = colorbar();
set(cb,'YTick', 0:5)
Option 2: control color range with caxis()
The range of integer values in your data is 6 but you've assigned 9 colors. If you want to scale the colors such that only the first 6 colors are used and the last 3 ignored, set the caxis() range from 0:9 instead of 0:5.
A=[1:3;2:4;3:5;0 0 0];
cmap = [0 0.5 0.5;0.75 0.75 0;1 0.75 0.25;
0.25 0 1;1 1 0.75;0.75 0 0.75;
0.75 0.75 0;0.25 0.25 0.25;1 0.5 0];
imagesc(A);
colorbar()
colormap(cmap);
caxis([0 9]); % <----
3 Kommentare
Adam Danz
am 13 Aug. 2019
Ivan, I've updated my answer and added "Option 2".
All you have to do is scale the color range from 0 to 9 instead of 0 to 5.
Let me know if you have any other questions.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Colormaps finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!