Effacer les filtres
Effacer les filtres

Automatic generation of Legend

36 vues (au cours des 30 derniers jours)
Snr Jhay
Snr Jhay le 10 Juin 2022
Commenté : Star Strider le 11 Juin 2022
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

Réponse acceptée

Star Strider
Star Strider le 10 Juin 2022
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 commentaires
Snr Jhay
Snr Jhay le 11 Juin 2022
Thanks a lot for the solution, advice, time and patience. I appreciate it
Star Strider
Star Strider le 11 Juin 2022
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by