Legend for variable number of plots

조회 수: 14 (최근 30일)
Kiran Sagar
Kiran Sagar 2016년 3월 9일
댓글: Kiran Sagar 2016년 3월 10일
Hi, I am plotting a variable 'y' whose size is 'm-by-n' against 'x' whose size is 'm-by-1'. So, I get 'n' plots on the current figure. Now, how can I write insert legend without knowing the value of n. I mean, how do I give dynamic input to legend function.
plot(x,y)
legend('Mode 1','Mode 2','Mode 3',...'Mode n')

채택된 답변

Guillaume
Guillaume 2016년 3월 9일
legend(arrayfun(@(mode) sprintf('Mode %d', mode), 1:size(y, 2), 'UniformOutput', false))
Would be one way of doing it.
  댓글 수: 3
Guillaume
Guillaume 2016년 3월 9일
편집: Guillaume 2016년 3월 9일
The arrayfun part builds a cell array of strings that is then passed to legend. It is equivalent to:
legendstrings = cell(1, size(y, 2)); %arrayfun automatically constructs a cell array the right size
for mode = 1:size(y, 2) %this is the second input of arrayfun
legendstrings{mode} = sprintf('Mode %d', mode); %1st input of arrayfun, sort of
end
legend(legendstrings);
Kiran Sagar
Kiran Sagar 2016년 3월 10일
Thank you very much. That was helpful

댓글을 달려면 로그인하십시오.

추가 답변 (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