Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a grouped 2 dimensional vector in MATLAB

Tags:

plot

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.

Now I want to plot these based on colors.

like image 525
Hossein Avatar asked Jan 23 '26 02:01

Hossein


1 Answers

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.

like image 158
Jonas Avatar answered Jan 26 '26 01:01

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!