3D scatter plot with different color and legend explaining each color.

Hi,I want to draw a 3D scatter plot with different colors and want to put a legend that explains what each color means.
My example is something like this.
b's are the data points that I want to put in the 3D scatter. b1=[1,2,3,4,5] b2=[2,2,3,3,1] b3=[1,5,4,4,3]
s is the size of the points s=[1,1,1,1,1]
r is the color of the points (three colors) r=[0,0,2,1,2]
Finally the scatter plot is this = scatter3(b1,b2,b3,s,r,'filled')
My questions are. 1)Can I set a designate color to each numbers in r? for example, red for 0, blue for 1, green for 2. if so, How can I do it?
2) how can I set a legend that explains what the color means? for example. for color 0 - 'efficient', for color 1 - 'inefficient', for color 2- 'not an eq'

 Accepted Answer

Try this:
b1=[1,2,3,4,5];
b2=[2,2,3,3,1];
b3=[1,5,4,4,3];
s=[1,1,1,1,1];
r=[0,0,2,1,2];
scatter3(b1,b2,b3,s*50,r,'filled')
% Define rgb colors manually:
colors = [1 0 0; % red
0 0 1; % blue
0 1 0];% green
colormap(colors);
cb = colorbar;
caxis([-0.5 2.5])
set(cb,'ytick',0:2,'yticklabel',{'efficient','inefficient','not an eq'})
I had to increase the size of the points (multiplied by 50) because otherwise they're too small to see.

4 Comments

Okay. I understand the color, you mean this [1 0 0; 0 0 1; 0 1 0]? But my question is, how to put a designate color to each numbers in r. So here in the example, I want to have [red,red,green,blue,green]. Can I do this?
I found how to use the color mapping. Thank you. For who may look at this, refer to this question and answer. Why couldn't I find this before...
https://www.mathworks.com/matlabcentral/answers/225193-grouping-data-for-a-3d-scatter-plot
Alternatively, you could use plot3 and plot each category of data separately like this:
b1=[1,2,3,4,5];
b2=[2,2,3,3,1];
b3=[1,5,4,4,3];
s=[1,1,1,1,1];
r=[0,0,2,1,2];
% get unique values of r:
ur = unique(r);
% Define rgb colors manually:
colors = [1 0 0; % red
0 0 1; % blue
0 1 0];% green
hold on;
view(3);
grid on
for k = 1:3
ind = r==ur(k); % indices corresponding to r=k
plot3(b1(ind),b2(ind),b3(ind),'.','markersize',30,'color',colors(k,:))
end
legend('efficient','inefficient','not an eq')
Thank you, this solution helped my problem :)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!