views:

126

answers:

3

I am trying to make a plot of a 2-dimensional vector (2D Plot). But I don't want all the datapoints to have the same color on the plot. Each datapoint corresponds to a group. I want to have different colors for each group of datapoints.

class=[1 3 2 5 2 5 1 3 3 4 2 2 2]

says each datapoint belongs to which group

X=[x1,y1;x2,y2;x3,y3;.....] 

the number of these datapoints are the same as the number of elements in the class vector.

Now I want to plot these based on colors.

+2  A: 

Firstly, since CLASS is a built-in function, I would name your vector classID instead.

Then, for each value in classID you can do the following:

index = (classID == 1);            %# Logical index of where classID is 1
plot(X(index,1),X(index,2),'r.');  %# Plot all classID 1 values as a red dot
hold on;                           %# Add to the existing plot
gnovice
Thank you, I found this also but yours is better:gscatter(m(:,2),m(:,1),classID,'brgyckm','o'). and thank you for the comment for "class".
Hossein
+4  A: 

You can use SCATTER to easily plot data with different colors. I agree with @gnovice on using classID instead of class, by the way.

scatter(X(:,1),X(:,2),6,classID); %# the 6 sets the size of the marker.

EDIT

If you want to display a legend, you have to either use @yuk's, or @gnovice solution.

GSCATTER

%# plot data and capture handles to the points
hh=gscatter(randn(100,1),randn(100,1),randi(3,100,1),[],[],[],'on');
%# hh has an entry for each of the colored groups. Set the DisplayName property of each of them
set(hh(1),'DisplayName','some group')

PLOT

%# create some data
X = randn(100,2);
classID = randi(2,100,1);
classNames = {'some group','some other group'}; %# one name per class
colors = hsv(2); %# use the hsv color map, have a color per class

%# open a figure and plot
figure
hold on
for i=1:2 %# there are two classes
id = classID == i;
plot(X(id,1),X(id,2),'.','Color',colors(i,:),'DisplayName',classNames{i})
end
legend('show')

You may also want to have a look at grouped data if you have the statistics toolbox.

Jonas
+1: Cool! I never noticed that fourth input to SCATTER.
gnovice
What is interesting, you can use vector same length as classID as 3rd argument to differentiate classes by symbol size. Try `scatter(X(:,1),X(:,2),classID*1000,'r.')` to plot the bubbleplot.
yuk
Thank you, I found this also but yours is better:gscatter(m(:,2),m(:,1),classID,'brgyckm','o')
Hossein
Is there any ways to get the legend for this?
Hossein
@Hossein: Not for scatter, but for the other two.
Jonas
+2  A: 

Look also at the GSCATTER function from Statistics Toolbox. You can specify color, size and symbol for each group just once.

gscatter(X(:,1),X(:,2),classID,'bgrcm');

or just

gscatter(X(:,1),X(:,2),classID); %# groups by color by default
yuk

related questions