Reputation: 66585
Along with 3 numeric values the data contains categorical value (0 or 1) and would like to display the data using 3D scatter plot. I have tried to write a function to read the data from csv file and create a scatter plot the following way:
function f = ScatterPlotUsers(filename)
data = ReadCSV(filename);
x = data(:,2);
y = data(:,3);
z = data(:,4);
size = ones(length(x), 1)*20;
userType = data(:,5);
colors = zeros(length(x), 1);
a = find(userType == 1);
b = find(userType == 0);
colors(a,1) = 42; %# color for users type a
colors(b,1) = 2; %# color for users type b
scatter3(x(:),y(:),z(:),size, colors,'filled')
view(-60,60);
What I actually wanted to do was to set the colour for a to red and b to blue but no matter the colour values (42 and 2 in example) the colours of dots don't change. Does anyone know what is the right way to determine specific colours for several categorical values (in this case only 0 and 1)?
Upvotes: 1
Views: 1666
Reputation: 3084
I'd use colormap, especially if your userType
values start at 0 and increase:
% Read in x, y, z, and userType.
userType = userType + 1;
colormap(lines(max(userType)));
scatter3(x, y, z, 20, userType);
If you want specific colors, replace lines(...)
with a matrix. For example, if you had 3 user types and you wanted them red, green, and blue:
colormap([1, 0, 0;
0, 1, 0;
0, 0, 1]);
A few other notes:
We add one to userType
to switch from 0-based indexing to 1-based indexing.
You can use a scalar for the size
parameters of scatter3 instead of specifying an array of a single value.
Upvotes: 2
Reputation: 38052
You are doing it right, however, are you sure the colormap entries 42 and 2 refer to red and blue? You could try to give RGB values explicitly:
colors = zeros(length(x), 3);
colors(userType == 1, :) = [1 0 0]; %# colour for users type a (red)
colors(userType == 2, :) = [0 0 1]; %# colour for users type b (blue)
Also, I'd advise you to change the name of the variable size
, since size
is also a Matlab command; Matlab might be confused about that, and any future readers of your code will certainly be confused about that.
Upvotes: 2