How do I plot one legend item for multiple plots?

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)

 Réponse acceptée

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)

Plus de réponses (0)

Produits

Version

R2021a

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by