Plotting Legend in a For Loop
조회 수: 4 (최근 30일)
이전 댓글 표시
I am trying to plot multiple lines on a plot, and want my legend to reflect those line styles as well as colors. I am using the following for loop-
for i=2:5
sigma_level=i; hold on;
h1=plot(x1,[meanf-sigma_level*stdf meanf-sigma_level*stdf],'Color',rand(1,3));
legendInfo{i-1}=[num2str(i),'\sigma'];
end;
legend(legendInfo)
My issue is that the legend does not reflect the lines plotted, because I'm not using the h1 variable to identify it in the legendInfo. If I use
legendInfo{i-1}=[h1,num2str(i),'\sigma']
I get the following error-
Error using matlab.graphics.chart.primitive.Line/horzcat
Conversion to matlab.graphics.chart.primitive.Line from char is not possible.
Error in test (line 33)
legendInfo{i-1}=[h1,num2str(i),'\sigma'];
What is the possible solution to fix this?
Thanks!
댓글 수: 0
채택된 답변
dpb
2016년 6월 28일
plot returns a line handle; you're overwriting the previous handles on the subsequent passes thru the loop...
j=0; % accumulator; not sure why ran loop 2:5??
for i=2:5
j=j+1;
sigma_level=i;
h(j)=plot(x1,[meanf-sigma_level*stdf meanf-sigma_level*stdf],'Color',rand(1,3));
if j==1, hold on, end % only set hold after first plot...
legendInfo{j}=[num2str(i),'\sigma'];
end;
legend(h,legendInfo)
댓글 수: 2
dpb
2016년 6월 30일
The magnitude of the multiplier is 2:5; that doesn't mean the loop had to be written that way (and thereby complicate the indexing).
추가 답변 (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!