Modify the color of a scatter3 plot

6 views (last 30 days)
Yoan
Yoan on 11 Aug 2023
Moved: Walter Roberson on 11 Aug 2023
I have the following command
scatter3(X,Y,Z,20,sector,'.')
The value 'sector' is responsile of the color. If I display it is like
sector = 1
1
1
...
2
2
2
...
3
3
3
But I would like to change the color associate to it in order to have a special red when sector is 1, a special blue for 2 and a special yellow when it's 3
How could I do

Answers (3)

dpb
dpb on 11 Aug 2023

Yoan
Yoan on 11 Aug 2023
Edited: dpb on 11 Aug 2023
I find a solution with this
sector_str=[];
for i = 1 : length(sector)
if sector(i) == 1
sector_str(i,:) = [1 0 0];
elseif sector(i) == 2
sector_str(i,:) = [0 0 1] ;
elseif sector(i) == 3
sector_str(i,:) = [1 1 0] ;
else
sector_str(i) = 'k' ;
end
end
scatter3(X,Y,Z,20,sector_str,'.')
  2 Comments
Steven Lord
Steven Lord on 11 Aug 2023
There's no need for a loop here. Let's make some sample data to show the technique.
sampleData = randi(4, 10, 1)
sampleData = 10×1
4 3 4 2 1 4 1 2 4 1
Here's the list of colors.
listOfColors = [1 0 0; 0 0 1; 1 1 0; 0 0 0]
listOfColors = 4×3
1 0 0 0 0 1 1 1 0 0 0 0
Now just use indexing to create the array of M-by-3 color data.
colors = listOfColors(sampleData, :)
colors = 10×3
0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0
dpb
dpb on 11 Aug 2023
"The MATLAB way" -- use vector lookup...don't need explicit loops/case/if..
CLRS=[[1 0 0];[0 0 1];[1 1 0]]; % the lookup table
X=randi([1 10],10,1);Y=randi([1 10],10,1);Z=randi([1 10],10,1);
sector=randi([1 3], size(X));
scatter3(X,Y,Z,[],CLRS(sector,:),'filled','markerEdgeColor','k')

Sign in to comment.


Walter Roberson
Walter Roberson on 11 Aug 2023
Moved: Walter Roberson on 11 Aug 2023
N = 10;
sector = randi(4, N, 1)
sector = 10×1
3 3 1 1 3 1 3 1 2 3
listOfColors = [1 0 0; 0 0 1; 1 1 0; 0 0 0]
listOfColors = 4×3
1 0 0 0 0 1 1 1 0 0 0 0
X=randi([1 10],N,1); Y=randi([1 10],N,1); Z=randi([1 10],N,1);
scatter3(X, Y, Z, [], sector);
colormap(listOfColors)

Categories

Find more on 2-D and 3-D Plots 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!