Plot Legend Not Correct

조회 수: 93 (최근 30일)
Bailey Smith
Bailey Smith 2018년 6월 27일
댓글: Parasram Siewlal 2019년 10월 15일
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')

채택된 답변

Adam Danz
Adam Danz 2018년 6월 27일
편집: Adam Danz 2018년 6월 27일
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
Bailey Smith
Bailey Smith 2018년 6월 27일
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 2019년 10월 15일
Thanks, I ran into the same problem and your solution helped.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Rik
Rik 2018년 6월 27일
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'})

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by