Effacer les filtres
Effacer les filtres

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

31 vues (au cours des 30 derniers jours)
the cyclist
the cyclist le 4 Fév 2013
Commenté : Anton le 9 Avr 2014
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];
figure
scatter(M(:),sort(M(:)),S,C,'filled')
Is there a simple way to create a legend to the three colors?

Réponse acceptée

bym
bym le 5 Fév 2013
Modifié(e) : bym le 5 Fév 2013
gscatter(M(:),sort(M(:)),C)
  1 commentaire
the cyclist
the cyclist le 5 Fév 2013
Yet another MATLAB function that I knew and then forgot. Thanks for the reminder!

Connectez-vous pour commenter.

Plus de réponses (1)

ChristianW
ChristianW le 5 Fév 2013
Without gscatter fcn:
[~, I] = unique(C);
p = findobj(gca,'Type','Patch');
legend(p(I),'X','Y','Z')
  1 commentaire
Anton
Anton le 9 Avr 2014
I'd like to add a correction to this solution, since it doesn't work properly in my case (8.2.0.701 (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');
legend(p(I),'X','Y','Z');

Connectez-vous pour commenter.

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by