Filter löschen
Filter löschen

Automatic generation of Legend

36 Ansichten (letzte 30 Tage)
Snr Jhay
Snr Jhay am 10 Jun. 2022
Kommentiert: Star Strider am 11 Jun. 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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by