How can i add legend in a for loop after each plot ?

227 views (last 30 days)
In below code legend got updated each times thereby leaving me with only the last legend but i want is like 1st iteration plot and its legend and next plot and its legends ;thereby all legends should be there.
for i=2:2:20
y=(P(:,1));
plot((P(:,i+1)),y,'color',rand(1,3),'marker','s')
h{i}=char(headings(i));
legend(h(i))
end

Accepted Answer

Walter Roberson
Walter Roberson on 11 Jun 2017
If you are using a fairly new version of MATLAB then see https://www.mathworks.com/help/matlab/ref/legend.html#bvk3tnk-1
for i=2:2:20
plot( P(:,i+1), P(:,1), 'color', rand(1,3), 'marker', 's', 'DisplayName', headings{i});
end
legend('show')
For older versions of MATLAB,
for i=2:2:20
plot( P(:,i+1), P(:,1), 'color', rand(1,3), 'marker', 's', );
end
legend( headings(2:2:20) );
or
for i=2:2:20
plot( P(:,i+1), P(:,1), 'color', rand(1,3), 'marker', 's', );
h{i} = headings{i};
end
legend( h(2:2:20) );
  9 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!