Problem in legend plot in case of empty variable [ ]

1 回表示 (過去 30 日間)
Federico Giannetti
Federico Giannetti 2022 年 4 月 6 日
コメント済み: Rik 2022 年 4 月 6 日
Hello everyone, I have a problem in a legend plot. In particular, the code is:
plot(x1,y1,'b')
plot(x2,y2,'r')
plot(x3,y3,'k')
plot(x4,y4,'m')
legend ('Plot 1', 'Plot 2', 'Plot 3', 'Plot 4')
For example, if y3 = [ ], the plot of y4 will be associated to 'Plot 3'. I would like that in case of y3 = [ ] the legend skips the corresponding 'Plot 3' and associate y4 to 'Plot 4'.
Any ideas?
Thank you all

回答 (1 件)

Rik
Rik 2022 年 4 月 6 日
I am going to assume your numbered variables are just to make this example easy to understand. If not: you should consider indexing a cell array instead.
As for you question: you can set the DisplayName property.
x1=rand(10,1);y1=rand(size(x1));
x2=rand(10,1);y2=rand(size(x1));
x4=rand(10,1);y4=rand(size(x1));
x3=[];y3=[];
h{1}=plot(x1,y1,'b','DisplayName','Plot 1');
hold on
h{2}=plot(x2,y2,'r','DisplayName','Plot 2');
h{3}=plot(x3,y3,'k','DisplayName','Plot 3');
h{4}=plot(x4,y4,'m','DisplayName','Plot 4');
legend([h{:}])
  2 件のコメント
Federico Giannetti
Federico Giannetti 2022 年 4 月 6 日
Perfect.
Thank you! It's working.
Rik
Rik 2022 年 4 月 6 日
You're welcome. If this solved your issue, please consider marking it as accepted answer. If not, feel free to comment with remaining issues.

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

カテゴリ

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