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

63 ビュー (過去 30 日間)
the cyclist
the cyclist 2013 年 2 月 4 日
コメント済み: Anton 2014 年 4 月 9 日
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?

採用された回答

bym
bym 2013 年 2 月 5 日
編集済み: bym 2013 年 2 月 5 日
gscatter(M(:),sort(M(:)),C)
  1 件のコメント
the cyclist
the cyclist 2013 年 2 月 5 日
Yet another MATLAB function that I knew and then forgot. Thanks for the reminder!

サインインしてコメントする。

その他の回答 (1 件)

ChristianW
ChristianW 2013 年 2 月 5 日
Without gscatter fcn:
[~, I] = unique(C);
p = findobj(gca,'Type','Patch');
legend(p(I),'X','Y','Z')
  1 件のコメント
Anton
Anton 2014 年 4 月 9 日
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');

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by