1

I have my data points and cluster number as follows:

X        Y       cluster
-0.42042 0.2071  0
-1.4986  -1.8658 0
-0.50905 -0.0751 0
2.1978   1.9568  1
1.4901   1.6177  1
1.6961   1.8293  1
1.6021   0.0857  1 
0.87831  0.71435 1
2.6688   1.3426  1
-1.741   0.90686 2
-1.8332  0.35599 2
-3.0733  0.42656 2
-2.1991  0.41843 2
-2.8099  0.93542 2
-1.3631  1.0914  2

The above data was unsorted, so I used sortrows to sort in terms of cluster number and I get the above data.

I have to plot these clusters. Is there any MATLAB function for plotting clusters? I know we can use something like this: plot(M(:,1), M(:,2), '.');

But this plot all values in one cluster. I have to plot in three clusters as per data. The clusters are 0, 1,2. So three clusters with three different colors should be plotted. So something like this:

enter image description here

Any idea how to go about it?

EBH
  • 10,350
  • 3
  • 34
  • 59
gpuguy
  • 4,607
  • 17
  • 67
  • 125

3 Answers3

2

So you can do it in several ways: You can use the current color map for the colors and simply :

scatter(x,y,'cdata',cluster,'marker','.');

or as you wrote in your code

scatter(M(:,1),M(:,2),'cdata',M(:,3),'marker','.');

you could also use a predefined color map instead of the default

ClusterColorMap=rand(max(M(:,3)),3); %random colormap
colormap(ClusterColorMap);
scatter(M(:,1),M(:,2),'cdata',M(:,3),'marker','.');

here ClusterColorMap would have 3 rows, each containing a specific color (in RGB format in the 3 columns chosen here as random). if you know the number of clusters in advanced you can set this matrix to have specific values.

itzik Ben Shabat
  • 927
  • 11
  • 24
  • If I consider your second method, please explain how this will print three clusters, for each of 0, 1,2? – gpuguy Oct 20 '16 at 05:50
  • Got me there, had a typo in my code and added some explenations. bw, you could do something similar with plot but for scattered point data scatter() is supposed to be better – itzik Ben Shabat Oct 20 '16 at 08:26
1

You'll need to divide you data into three groups and plot them individually. Something like this assuming you have three variables X, Y, and cluster:

grp1 = cluster==0;
grp2 = cluster==1;
grp3 = cluster==2;

Then plot each group individually:

plot(X(grp1),Y(grp1),'.', X(grp2),Y(grp2),'.', X(grp3),Y(grp3),'.')
Justin
  • 1,980
  • 1
  • 16
  • 25
  • thanks for your advice. How do we divide this data into three groups ? – gpuguy Oct 20 '16 at 04:13
  • @gpuguy You divide the data into 3 groups as shown in the answer, using the `grp1`, `grp2` and `grp3` variables. Try the code and inspect the variables, it should become clear... – Justin Oct 20 '16 at 12:39
1

Here is a direct way to do this:

gscatter(x,y,cluster)

Here is an example with your data:

clusters

and if you want to set the colors, symbols, etc...

gscatter(x,y,cluster,'cmk','p*^')

cluster2

EBH
  • 10,350
  • 3
  • 34
  • 59