필터 지우기
필터 지우기

Legend for two plots only applies to second plot

조회 수: 3 (최근 30일)
z8080
z8080 2016년 6월 23일
답변: dpb 2016년 6월 23일
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