Effacer les filtres
Effacer les filtres

Plot Legend Not Correct

59 vues (au cours des 30 derniers jours)
Bailey Smith
Bailey Smith le 27 Juin 2018
So I have a code and want to plot a couple of features. Long story short, my plot legend is a little confused as to its labels. How can I correct this?
clear;clc;
%inputs
d=5; %feet
h=10; %feet
yi=7; %feet
ysp=5; %feet
dt=30; %seconds
band=1; %feet
%givens
Vimax=100; %gallons per minute
Vimax=Vimax*0.002228; %ft^3/s
aTank=(pi*d^2)/4; %ft^2
tmax=3000;
uL=ysp+band/2;
lL=ysp-band/2;
%valve position
if yi>uL
vp=0;
elseif yi<lL
vp=1;
else
vp=0;
end
t=0;
y=yi;
n=1;
while t(n)<=tmax
%net flow rate
nfl=Vimax*vp-Vout(t); %ft^3/s
%net volume change for a time step
vc=nfl*dt; %ft^3
%determine change in water level
dy=vc/aTank; %feet
y(n+1)=y(n)+dy;
t(n+1)=t(n)+dt;
%next
if y(n+1)>uL
vp=0;
elseif y(n+1)<lL
vp=1;
else
vp=vp;
%vp=-(y(n+1)-ysp)/band+0.5; %CHANGE TO PROPORTIONAL
end
n=n+1;
end
plot(t,y,'r')
hold on
plot(t,ysp,'g+')
plot(t,uL,'bo')
plot(t,lL,'y.')
xlabel('Time in Seconds')
ylabel('Water Level in Feet')
legend('Water Level','Setpoint','Upper Level','Lower Level')

Réponse acceptée

Adam Danz
Adam Danz le 27 Juin 2018
Modifié(e) : Adam Danz le 27 Juin 2018
The reason your legend has duplicate symbols is because there are multiple elements plotted for each marker. This is one of the reasons why you should used handles when you call legend().
Replace the plotting section after the while loop with this.
h1 = plot(t,y,'r');
hold on
h2 = plot(t,ysp,'g+');
h3 = plot(t,uL,'bo');
h4 = plot(t,lL,'y.');
xlabel('Time in Seconds')
ylabel('Water Level in Feet')
legend([h1,h2(1),h3(1),h4(1)], 'Water Level','Setpoint','Upper Level','Lower Level')
By the way, I couldn't run your code because the value of 'Vout' is unknown.
  2 commentaires
Bailey Smith
Bailey Smith le 27 Juin 2018
I have a function that's called into the code. I totally forgot about that. My bad. And thank you so much for the help!
Parasram Siewlal
Parasram Siewlal le 15 Oct 2019
Thanks, I ran into the same problem and your solution helped.

Connectez-vous pour commenter.

Plus de réponses (1)

Rik
Rik le 27 Juin 2018
You can use the output of the plot function to get the handles to the objects. Then you can use the list as an input to legend.
temp=plot(t,y,'r');
plothandles=temp(1);
hold on
temp=plot(t,ysp,'g+');
plothandles(2)=temp(1);
temp=plot(t,uL,'bo');
plothandles(3)=temp(1);
temp=plot(t,lL,'y.');
plothandles(4)=temp(1);
xlabel('Time in Seconds')
ylabel('Water Level in Feet')
legend(plothandles,{'Water Level','Setpoint','Upper Level','Lower Level'})

Community Treasure Hunt

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

Start Hunting!

Translated by