Legend and for loops

Hey, I am trying to evaluate some data and show it in a graph consisting of 3 sets each containg Mean values, x-errorbars and a fit function (See picture). But I am only able to get a part of the legend showing the right color for the last itteration or I get the whole legend but the color of my 'mean values' is set to that of the last itteration (symbol is ok). I tried numerus approaches but nothing seems to work. My latest try is this code ():
for (3 times itteration)...... other stuff goin on.....
[h,hh]= errorbar_x_one(eval_complete(2,:),eval_complete(1,:),eval_complete(3,:)); %errorbar_x_one outputs handle of errorbar and handle of scatter
y_loudness_function = loudness_function(x_achse,eval_line_point);%loudness function fit
hhh = plot(x_achse,y_loudness_function,[col_sym.col{col_sym.xxx} ':']);
grid on
col_sym.xxx = col_sym.xxx+1;
h.DisplayName = 'Errorbar';
hh.DisplayName = ['Mean ' condition{col_sym.xxx}] ;
hhh.DisplayName = 'fit';
end
legend([h hh hhh],'Location','NW')
Any help would be greatly appreciated.

Answers (1)

You're saying you call
legend([h hh hhh], ...)
each time around the loop? That means that each time you're telling legend to forget about the items from the previous iteration and focus on these 3 new objects.
You'll want to move legend out of the loop. You could do something like this:
g = gobjects(1,9);
for i=1:3
[h, hh] = errorbar_x_one( ...
hhh = plot( ...
g(end+1) = h;
g(end+1) = hh;
g(end+1) = hhh;
end
legend(g)
But if you're really putting everything into the legend, then you don't need to give it the handles. So you may be able to do something as simple as this:
for i=1:3
[h, hh] = errorbar_x_one( ...
hhh = plot( ...
end
legend show

3 Comments

Elduderino
Elduderino on 17 Feb 2016
Edited: Elduderino on 17 Feb 2016
Hey, this call of the legend function was sorta during the trial and error phase I just wanted to check if the color is ok druing the loop and it is. But outside it shows the wrong color. The 'gobjcts' function is really handy thanks for that adivce! I was doing this by foot. However the legend(show) and the g = gobject legend(g,....) show the incorrect color for the mean values again.
Elduderino
Elduderino on 17 Feb 2016
Edited: Elduderino on 17 Feb 2016
Hey,
thanks for that info! I was thinking it might be the fact that the handle of the scatter plot has no color field. But this feature seems to be what I am experiencing.
Btw. do I understand this correct that the workaround's idea is to define a color pattern in advance and then pass that info in the legend?
edit: I used line plot instead...

Sign in to comment.

Asked:

on 17 Feb 2016

Edited:

on 17 Feb 2016

Community Treasure Hunt

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

Start Hunting!