Plotting a grouped 2 dimensional vector in MATLAB
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.
N开发者_JAVA技巧ow I want to plot these based on colors.
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.
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
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
精彩评论