Problem in legend plot in case of empty variable [ ]

1 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Legend 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by