Borrar filtros
Borrar filtros

Automatic generation of Legend

36 visualizaciones (últimos 30 días)
Snr Jhay
Snr Jhay el 10 de Jun. de 2022
Comentada: Star Strider el 11 de Jun. de 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

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by