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

3d plotsscatter plotStatistics and Machine Learning Toolbox

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.
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'

Best Answer

Try this:
fontSize = 20;
numPoints = 30;
b1 = randi(9, 1, numPoints);
b2 = randi(9, 1, numPoints);
b3 = randi(9, 1, numPoints);
% markerSize is the size of the markers.
markerSize = 100;
% customColorMap is the color of the points (three colors)
% Option 1: Use the built-in "jet" colormap.
% customColorMap = jet(numPoints);
% Option 2: Make up a custom one.
customColorMap = zeros(numPoints, 3); % Initialize.
% Make the first 10 points red
customColorMap(1:10, :) = repmat([1, 0, 0], 10, 1);
% Make the next 10 points dark green
customColorMap(11:20, :) = repmat([0, 0.6, 0], 10, 1);
% Make the remaining points blue
customColorMap(21:end, :) = repmat([0, 0, 1], 10, 1);
% Create the scatter plot.
scatter3(b1, b2, b3, markerSize, customColorMap,'filled')
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
zlabel('Z', 'FontSize', fontSize);