Plotting Legend in a For Loop
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
dpb
am 28 Jun. 2016
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 Kommentare
dpb
am 30 Jun. 2016
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).
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!