Plotting Legend in a For Loop

4 vues (au cours des 30 derniers jours)
Mridul Garg
Mridul Garg le 28 Juin 2016
Commenté : dpb le 30 Juin 2016
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!

Réponse acceptée

dpb
dpb le 28 Juin 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 commentaires
Mridul Garg
Mridul Garg le 28 Juin 2016
Thank you, this works perfectly fine.
PS- It's specific to the problem so I need to run it from 2-5.
dpb
dpb le 30 Juin 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).

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by