Automatic generation of Legend

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

请先登录,再进行评论。

更多回答(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