cs0815
cs0815

Reputation: 17418

conditional scatter in matlab

Is it possible to scatter in matlab (2D) where the color of the marker is conditioned on a third column. I can use loops and hold on but maybe there is a simpler way.

Christian

Upvotes: 1

Views: 1057

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24127

@Bill's answer is fine, but if you have access to Statistics Toolbox you could also try gscatter.

Upvotes: 2

Bill Cheatham
Bill Cheatham

Reputation: 11937

The fourth argument to scatter allows you to specify a colour. From the documentation:

scatter(X,Y,S,C)

...

C determines the color of each marker. When C is a vector the same length as X and Y, the values in C are linearly mapped to the colors in the current colormap. When C is a 1-by-3 matrix, it specifies the colors of the markers as RGB values. If you have 3 points in the scatter plot and wish to have the colors be indices into the colormap, C should be a 3-by-1 matrix. C can also be a color string (see ColorSpec for a list of color string specifiers).

Try something like:

X = rand(1, 10);
Y = rand(1, 10);
colour = randi(3, 1, 10)

colour =

 2     1     3     1     3     1     2     2     3     1

scatter(X, Y, [], colour, 'filled');

enter image description here

If your datasets are large, and there are few different colour categories, I tend to find that using plot with hold on is a faster way to plot.

Upvotes: 5

Related Questions