pmichna
pmichna

Reputation: 4888

How to make 2D scatter plot in Matlab with colors depending on values?

I have three vectors of the same lenght: x, y, and cls. I want to make a 2D plot of x and y but each point should have a color corresponding to the value of cls.

I thought about using the scatter function but you can chage the color of the whole plot, not of particular elements. Any ideas?

I would like to get something like in this example, when cls has elements of three values:

enter image description here

Upvotes: 1

Views: 14806

Answers (4)

paul Mazoyer
paul Mazoyer

Reputation: 11

One very simple solution with c being the color vector:

scatter3(X,Y,zeros(size(X,1)),4,c);    
view(0,90);

Upvotes: 0

nkjt
nkjt

Reputation: 7817

If you have the Statistics Toolbox, there is an easy way of doing this, it's called gscatter.

It takes similar inputs to scatter, but the third input is the group:

gscatter(x,y,cls)

You can add colours and markers - this plots with red, then green, then blue (order determined by the contents of cls, all markers circles.

gscatter(x,y,cls,'rgb','o')

Upvotes: 2

am304
am304

Reputation: 13886

Here's another solution splitting your data in three using logical indexing:

% Some random data
x = rand(100,1);
y = rand(100,1);
cls = round(2*rand(100,1));

% Split the data in three groups depending on the value in cls
x_red = x(cls==0);
y_red = y(cls==0);
x_green = x(cls==1);
y_green = y(cls==1);
x_blue = x(cls==2);
y_blue = y(cls==2);

% plot the data
scatter(x_red,y_red,1,'r')
hold on
scatter(x_green,y_green,1,'g')
scatter(x_blue,y_blue,1,'b')
hold off

Upvotes: 0

Ander Biguri
Ander Biguri

Reputation: 35525

From the help of scatter:

scatter(x,y,a,c) specifies the circle colors. To plot all circles with the same color, specify c as a single color string or an RGB triplet. To use varying color, specify c as a vector or a three-column matrix of RGB triplets.

you can construct c as

c=zeros(size(x),3);
c(cls==1,:)=[1 0 0]; % 1 is red
% ...
scatter(x,y,1,c)

However, I dont know how to do the background. Did you apply some Machine learning algorithm to clasify the data? maybe you can get the equations to plot the background from there, but it depends on the method.

Upvotes: 2

Related Questions