How can I use legend for plotting dynamically sized matrix?

조회 수: 1 (최근 30일)
Emin Yilmaz
Emin Yilmaz 2019년 12월 18일
댓글: Adam Danz 2021년 9월 3일
I'm trying to plot a matrix that's returned from a function. The size of the matrix is 3xN, N is accepted with input. This is what I'm trying to get to work:
for i = 1:length(T(1,:))
plot(T(:,i));
legend([ num2str(i-1) '. Generation']);
end
but the legend is assigned only to the plot of the first column of the matrix for i's max value. Is it possible to get it to work properly? MATLAB_ddvQVSBkhw.png

채택된 답변

Adam Danz
Adam Danz 2019년 12월 18일
편집: Adam Danz 2019년 12월 18일
Your loop is continuously overwriting the legend and only including the most recently plotted line. You actually don't need a loop at all.
T = randi(10,3,5); % fake data
plot(T)
legendStr = compose('%d Generation',(1:size(T,2))-1);
legend(legendStr)
If, for whatever reason, you prefer to produce the plot within a loop, here is the correct way to do that.
T = randi(10,3,5); % fake data
axes()
hold on
for i = 1:size(T,2)
plot(T(:,i),'DisplayName', sprintf('%d Generation',i-1));
end
legend() % no need for inputs since we used DisplayName
  댓글 수: 4
Robin Amar
Robin Amar 2021년 9월 3일
편집: Robin Amar 2021년 9월 3일
Hello Adam,
As I had similar requirement, therefore, I tried your option 1 with my code.
But, I cannot see multiple entries in the Legend display.
My Code:
phi = linspace(-4*pi, 4*pi, 30);
legendStr = compose('Angle: %s', int2str(phi));
legend(legendStr);
The output is as seen below (only one entry for all the traces):
Actually, I expected the output to be something like (independent entry for every trace):
Any Suggestions...??
Adam Danz
Adam Danz 2021년 9월 3일
I only see one line in your plot so there's only going to be one legend entry per line.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by