Plotting Legend in a For Loop
8 ビュー (過去 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!