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!