Problem in legend plot in case of empty variable [ ]

2 visualizaciones (últimos 30 días)
Federico Giannetti
Federico Giannetti el 6 de Abr. de 2022
Comentada: Rik el 6 de Abr. de 2022
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

Respuestas (1)

Rik
Rik el 6 de Abr. de 2022
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 comentarios
Federico Giannetti
Federico Giannetti el 6 de Abr. de 2022
Perfect.
Thank you! It's working.
Rik
Rik el 6 de Abr. de 2022
You're welcome. If this solved your issue, please consider marking it as accepted answer. If not, feel free to comment with remaining issues.

Iniciar sesión para comentar.

Categorías

Más información sobre Legend en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by