フィルターのクリア

Adding a legend manually for a plot generated by a loop

4 ビュー (過去 30 日間)
Osh
Osh 2016 年 1 月 26 日
コメント済み: Osh 2016 年 1 月 26 日
Hi,
I am generating a plot in Matlab one point at a time depending on how a condition is satisfied within a loop:
for i=1:size(Ind,1)
if(Ind(i)==1)
c='ro';
elseif(Ind(i)==2)
c='bo';
elseif(Ind(i)==3)
c='go';
end
plot(i,Y(i),c) %plotting some other value with the color chosen.
hold on
end
How do I add a legend entry to this? I want to associate the index position(1,2 and 3) to red,blue and green in the legend.
Thanks!

採用された回答

jgg
jgg 2016 年 1 月 26 日
編集済み: jgg 2016 年 1 月 26 日
I think the issue is that you don't want to generate the plot like that; it's slow and makes it hard to label. Check out this solution instead:
Y = 10*rand(100,1); %your data
Ind = rand(100,1) > 0.5;
Ind = Ind + (rand(100,1) > 0.75);
Ind = Ind + 1; %an index corresponding to the group/colour of Y
Vals = [1:100]'; %the X-axis, or location of Y
plot(Vals(Ind == 1),Y(Ind ==1), 'ro', Vals(Ind == 2), ...
Y(Ind == 2), 'bo', Vals(Ind == 3), Y(Ind == 3), 'go')
legend('Red Data', 'Blue Data', 'Green Data')
This is much more efficient and you don't have to loop over all your points.
So, in your example, you would just go:
i = [1:size(Ind,1)];
plot(i(Ind == 1),Y(Ind ==1), 'ro', i(Ind == 2), ...
Y(Ind == 2), 'bo', i(Ind == 3), Y(Ind == 3), 'go')
legend('Red Data', 'Blue Data', 'Green Data')
  1 件のコメント
Osh
Osh 2016 年 1 月 26 日
Thank you! That's exactly what I was looking for.

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

その他の回答 (0 件)

カテゴリ

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