Legend in for loop
2 views (last 30 days)
Show older comments
Good evening
In the following code, I am having 8 plots at the end, for one distance value I have two plots. One for LoS path, the other for NLoS path.But all in one figure. I tried to put a legend but it gives me an error. What is the correct syntax to do it?
thank you
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
plot(p.f,HL)
hold on
plot(p.f,HN)
end
hold off
0 Comments
Answers (1)
Adam Danz
on 27 Oct 2018
What code did you use to produce your legend and what was the error? Do you want a legend for each subplot or 1 legend for the whole figure? There's lots of ways to go about this depending on what you're looking for. Here's a general solution that can be adapted to your needs.
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
p1 = plot(p.f,HL);
hold on
p2 = plot(p.f,HN);
end
legend([p1,p2], {'HL', 'HN'})
hold off
Another solution I often prefer is using the 'DisplayName' property.
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
p1 = plot(p.f,HL, 'DisplayName', 'HL');
hold on
p2 = plot(p.f,HN, 'DisplayName', 'HN');
end
legend([p1,p2])
hold off
4 Comments
Adam Danz
on 28 Oct 2018
Your line of code
legendInfo{k} = ['LoS, d=' R(k) , 'NLoS, d=' R(k)];
is incorrect because the numerical values are not converted to strings.
My line of code
legendInfo{k} = sprintf('LoS, d=%d, NLoS, d=%d', R(k), R(k));
correctly converts the numerical values to strings. However, you still need to use the plot handles to correctly pair the plot elements with the legend text. Look at my answer again and you'll see how I use the plot handles in the legend. You can also play around with the sprintf command to suit your needs. Let me know if you have any follow-up questions.
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!