MATLAB Answers

the cyclist

Simplest way to add a legend to the groups of a scatter plot

Asked by the cyclist
on 4 Feb 2013
Latest activity Commented on by Anton
on 9 Apr 2014
Accepted Answer by bym

Here is a trivial scatter plot that uses the default marker size (S=[]) and a vector C to assign three colors according to the current colormap.

M = magic(3);
S = [];
C = [1;1;1;2;2;2;3;3;3];

Is there a simple way to create a legend to the three colors?



2 Answers

Answer by bym
on 5 Feb 2013
Edited by bym
on 5 Feb 2013
 Accepted answer

  1 Comment

the cyclist
on 5 Feb 2013

Yet another MATLAB function that I knew and then forgot. Thanks for the reminder!

Answer by ChristianW
on 5 Feb 2013

Without gscatter fcn:

[~, I] = unique(C);
p = findobj(gca,'Type','Patch');

  1 Comment

on 9 Apr 2014

I'd like to add a correction to this solution, since it doesn't work properly in my case ( (R2013b)). The problem appears, when the number of elements corresponding to different colors is not the same, for instance:

C = [1;1;1;1;2;3;3;3;3];

As far as I understand, order of handles provided by findobj is inverted: point corresponding to the first element of M has the last position in the array p.

I suggest the following solution:

[~, I] = unique(C); %
I = length(C) - I(length(I):-1:1); 
p = findobj(gca,'Type','Patch');

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!