Add legend to each figure()???

I have 3 diffrent figure and need to add legend to all the plots. I am having issue with adding legend to individual figures.
figure(1);
plot(P1);
hold on;
plot(P2);
hold on;
plot(P3);
hold on;
plot (TotalDemand);
hold on;
plot(TotalSupply);
%second plot
figure(2);
stairs(P1);
hold on;
stairs(P2);
hold on;
stairs(P3);
hold off;
%
figure(3)
stairs (TotalDemand);
hold on;
stairs(TotalSupply);
hold on;
stairs(Ene_Unserved);

4 Comments

Sajeer Modavan
Sajeer Modavan on 16 Feb 2020
Edited: Rik on 16 Feb 2020
figure
plot(P1);hold on
plot(P2)
plot(P3)
plot (TotalDemand)
plot(TotalSupply)
legend({P1, P2, P3, TotalDemand,TotalSupply})
you don’t need to write hold on again and again, just mention after first plot
You can set as required here
@Kalyan I would suggest posting your comment as an answer.
Note that Mohamed shows legend() being called before figure(2) is called.
It is possible to add a legend to an axes that is not the "current" axes, but it requires finding the handle to the axes.

Sign in to comment.

Answers (1)

You need to make the x and y data separately, like this:
figure(1)
plot(x,P1)
hold on
plot(x,P2)
plot(x,P3)
plot(x,TotalDemand)
plot(x,TotalSupply)
hold off
legend('P1','P2','P3','TotalDemand','TotalSupply')
figure(2)
stairs(x,P1)
hold on
stairs(x,P2)
stairs(x,P3)
hold off
legend('P1','P2','P3')
figure(3)
stairs(TotalDemand)
hold on
stairs(TotalSupply)
stairs(Ene_Unserved)
hold off
legend('TotalDemand','TotalSupply','Ene_Unserved')

Tags

Asked:

on 16 Feb 2020

Answered:

on 16 Feb 2020

Community Treasure Hunt

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

Start Hunting!