MATLAB: Legend for two plots only applies to second plot

legend

I need to plot data of two vectors, and want the data points of each to be shown in a different colour that is explaned in a legend. However, the code below displays only the legend for the second one. What am I doing wrong?
for i_plot = 1 : plot_step : N
subplot(N, 1, i_plot)
h_A = plot(bookmarksA(i_plot, :),0,'b.','MarkerSize',24);
legend('a');
xlim ([0 pieceDuration])
set(gca, 'yTick', []);
title(subj_string(i_plot,:))
hold on
h_Z = plot(bookmarksZ(i_plot, :),0,'r.','MarkerSize',24);
legend(h_Z, 'z');
end

Best Answer

for i_plot = 1 : plot_step : N
subplot(N, 1, i_plot)
h_A = plot(bookmarksA(i_plot, :),0,'b.','MarkerSize',24);
xlim ([0 pieceDuration])
set(gca, 'yTick', []);
title(subj_string(i_plot,:))
hold on
h_Z = plot(bookmarksZ(i_plot, :),0,'r.','MarkerSize',24);
legend([h_A h_Z],'a','z');
end
The problem with the legend is there's only one per axes and subsequent calls destroy an existing one and create a new one. Need to make the legend for all the lines its to apply to at one time. NB: If N is anything >1 the loop will overwrite the line handles h_A, h_Z on the second and subsequent passes which doesn't really hurt what's shown here but if one wants/needs the earlier handles later for further modifications, you'll have to go "handle-diving" for them. Better would be to create some arrays so they're unique and retrievable by the associated subplot and line. Without knowing more of the intent of the end result it's hard to say too much in detail but if the object is just two lines there really probably isn't a need for a loop at all.