Legend for two plots only applies to second plot

1 次查看(过去 30 天)
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

采纳的回答

dpb
dpb 2016-6-23
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by