필터 지우기
필터 지우기

Automatic generation of Legend

조회 수: 36 (최근 30일)
Snr Jhay
Snr Jhay 2022년 6월 10일
댓글: Star Strider 2022년 6월 11일
I have a program which asks users for vectors. These vectors are used to plot graphs based on previous data in the code. The user is able to specific as many numbers as possible and these are plotted. I want to add a legend that can automatically adjust to fit the number of points the user specifies. 'n' is the user specified vector
for n = [1 50 23 9]
ii = 11 +1;
plot(x, u(:,n+1))
xlabel('x(m)')
ylabel('t(s)')
title('Graph of U against x for specified time intervals')
legend (['t = ', num2str(n)])
grid on
hold on
end

채택된 답변

Star Strider
Star Strider 2022년 6월 10일
In the legend documentation, see the section on Specify Legend Labels During Plotting Commands.
Specifically here:
plot(x, u(:,n+1), 'DisplayName',sprintf('t = %2d',n))
and remove the legend call within the loop.
Then after the loop, the legend call is simply either:
legend
or:
legend('Location','best')
or something similar.
So the code would be something like this:
figure
hold on
for n = [1 50 23 9]
ii = 11 +1;
plot(x, u(:,n+1), 'DisplayName',sprintf('t = %2d',n))
xlabel('x(m)')
ylabel('t(s)')
title('Graph of U against x for specified time intervals')
grid on
end
hold off
legend('Location','best')
There are likely better ways to code the loop, however since this appears to be a section of larger code, I will leave it as is.
.
  댓글 수: 6
Snr Jhay
Snr Jhay 2022년 6월 11일
Thanks a lot for the solution, advice, time and patience. I appreciate it
Star Strider
Star Strider 2022년 6월 11일
As always, my pleasure!

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

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