legend for multiple plots

2 views (last 30 days)
nadia naji
nadia naji on 31 May 2022
Commented: Voss on 31 May 2022
Hello,
I have 4 matrix with 6 rows and 15 columns. I want to plot all these matrix in on plot. for this aim I used the followin code:
x=1:15
plot(x,res540,'-r')
hold on
plot(x,res720,'--b');
plot(x,res900,'-.g');
plot(x,res1080,':k','LineWidth',0.2);
now I need to put a legend for above code in one plot. but each method I used for it does not work or all legend has same color and style. what should I do for this? Thanks

Accepted Answer

Voss
Voss on 31 May 2022
% some matrices:
res540 = rand(6,15);
res720 = 1+rand(6,15);
res900 = 2+rand(6,15);
res1080 = 3+rand(6,15);
% store the line handles returned from plot;
% each plot call returns 6 lines
h = zeros(6,4);
x=1:15;
h(:,1) = plot(x,res540,'-r');
hold on
h(:,2) = plot(x,res720,'--b');
h(:,3) = plot(x,res900,'-.g');
h(:,4) = plot(x,res1080,':k','LineWidth',0.2);
% make a legend for the 1st line returned from
% each plot call (i.e., first row of h)
legend(h(1,:),{'540' '720' '900' '1080'})
  2 Comments
nadia naji
nadia naji on 31 May 2022
Great. Thank you.
Voss
Voss on 31 May 2022
You're welcome!

Sign in to comment.

More Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 31 May 2022
Use the outputs from plot to explicitly control what is show in the legend:
x=1:15
ph1 = plot(x,res540,'-r');
hold on
ph2 = plot(x,res720,'--b');
ph3 = plot(x,res900,'-.g');
ph4 = plot(x,res1080,':k','LineWidth',0.2);
legend([ph1(1),ph2(1),ph3(1),ph4(1)],'t1','t2','t3','t4')
HTH

Products


Release

R2016a

Community Treasure Hunt

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

Start Hunting!