How do I plot one legend item for multiple plots?
조회 수: 7 (최근 30일)
이전 댓글 표시
How can I label multiple plots with one legend item?
For example, I have 5 different plots and I want my legend to only contain "random plot is even" and "random plot is odd" and the plots with the same label should have the same colour. The only solution I found that comes close to it is below. The problem is that the labeling of the plots occurs multiple times and the plots with the same label have different colours.
clear all; close all;
figure; hold on;
for iter =1:5
rand_iter = rand(1,5);
plot(rand_iter)
if(mod(iter,2))
legend_iter{iter} = sprintf(['random plot is ', 'odd']);
else
legend_iter{iter} = sprintf(['random plot is ', 'even']);
end
end
legend(legend_iter)
댓글 수: 0
채택된 답변
Cris LaPierre
2021년 4월 13일
One approach I can think of is to check even/odd before you plot, and use line objects to control what is placed in the legend.
for iter =1:5
rand_iter = rand(1,5);
if(mod(iter,2))
lh(1) = plot(rand_iter,'b','DisplayName','random plot is odd');
hold on
else
lh(2) = plot(rand_iter,'r','DisplayName','random plot is even');
hold on
end
end
hold off
legend(lh)
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
