How to add a legend to a graph with multiple lines

8 views (last 30 days)
Hi,
How to I add an automated legend to show eachline, where there is a varying constant in the graph equation ('alpha').
My current solution is to write the following but I imagine there is a simpler way.
Thanks
Script:
% G_20_tanksim1: Dynamic tank simulation - Using solution by substitution
% of algebraic variables (Method 1)
% Extra Parameters
tf = 72; %h
h0 = 2; %m
% Solve the DAE
opts = odeset('RelTol',1e-5);
for alpha = 0.01:0.02:0.2 %Evaluating Alpha values for leakage rate
[t,h] = ode45(@(t,h)G_20_tankf1(t,h,alpha),[0 tf],h0,opts);
% Plot the graph
plot(t,h)
legend ('0.01','0.03','0.05','0.07','0.09','0.11','0.13','0.15','0.17','0.19');
hold on
title('G20 tanksim1')
xlabel('Time (h)')
ylabel('Level (m)')
grid on
end
Function:
function dhdt = G_20_tankf1(t,h,alpha) %function definition
% G_20_tankf1: Tank level Model
%Derivative function solution for Method 1
%(Subsitution of Algebriac Variables)
%Tank Model parameters and constants
A = 8; %m^2
CV1 = 2; %(m^3/min)/(kPa^0.5)
P0 = 100; %kPa
P1 = P1function(t); %kpa
P3 = 100; %kPa
rho = 1000; %kg/m^3
g = 9.81; %m/s^2
% Algebraic equations for F1, F2, F3, P2 and CV2 have been sunstituted
% into the differential equation for dh/dt to create a pure ODE system
dhdt = 1/A*(CV1*sqrt(P1-P0-rho*g*h/1000) - 3*h*sqrt(P0+rho*g*h/1000-P3) - alpha*g*h);
%Where 'alpha*g*h'= Leakage rate

Answers (2)

Adam
Adam on 4 Dec 2018
You can pass labels to the legend function in a cell array so you can create that dynamically as e.g.
legend( arrayfun( @num2str, alpha, 'UniformOutput', false ) )
I don't understand what you are doing creating the full legend within the loop that is doing the plots though. You should just be able to add the legend at the end. I would have thought it would throw an error because you are trying to give it more labels than their are plots for all but the last time round the loop, but maybe it just ignores the excess labels, I can't remem,ber off-hand.

Star Strider
Star Strider on 4 Dec 2018
You need to set ‘alpha’ as a separate vector, then use compose or the undocumented function sprintfc to create the legend string:
alpha = 0.01:0.02:0.2;
for k = 1:numel(alpha) %Evaluating Alpha values for leakage rate
[t,h] = ode45(@(t,h)G_20_tankf1(t,h,alpha(k)),[0 tf],h0,opts);
% Plot the graph
plot(t,h)
legend(compose('%.2f', alpha)) % Create Legend String
legend(sprintfc('%.2f',alpha)) % Create Legend String
...
end

Tags

Community Treasure Hunt

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

Start Hunting!