Legend in for loop
조회 수: 5 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Adam Danz
2018년 10월 27일
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
Adam Danz
2018년 10월 28일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!