How do I plot one legend item for multiple plots?

16 visualizaciones (últimos 30 días)
Maxim
Maxim el 13 de Abr. de 2021
Respondida: Cris LaPierre el 13 de Abr. de 2021
How can I label multiple plots with one legend item?
For example, I have 5 different plots and I want my legend to only contain "random plot is even" and "random plot is odd" and the plots with the same label should have the same colour. The only solution I found that comes close to it is below. The problem is that the labeling of the plots occurs multiple times and the plots with the same label have different colours.
clear all; close all;
figure; hold on;
for iter =1:5
rand_iter = rand(1,5);
plot(rand_iter)
if(mod(iter,2))
legend_iter{iter} = sprintf(['random plot is ', 'odd']);
else
legend_iter{iter} = sprintf(['random plot is ', 'even']);
end
end
legend(legend_iter)

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 13 de Abr. de 2021
One approach I can think of is to check even/odd before you plot, and use line objects to control what is placed in the legend.
for iter =1:5
rand_iter = rand(1,5);
if(mod(iter,2))
lh(1) = plot(rand_iter,'b','DisplayName','random plot is odd');
hold on
else
lh(2) = plot(rand_iter,'r','DisplayName','random plot is even');
hold on
end
end
hold off
legend(lh)

Más respuestas (0)

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by