Effacer les filtres
Effacer les filtres

How do I add legends to my plot?

3 vues (au cours des 30 derniers jours)
Macarena Santillan
Macarena Santillan le 9 Fév 2022
Commenté : Star Strider le 9 Fév 2022
Hello I have a code to plot a couple of line sin different colors and I wanted to add a nox with the name of each function but for some reason the names are being displayed twice.
Does anyone know why this happens or how this can be fixed?
Thank you (:

Réponse acceptée

Star Strider
Star Strider le 9 Fév 2022
There are apparently two lines for every channel. There are two options:
The first is to simply plot the first row rather than both rows:
plot(Ch1(1,4:end), 'g', 'DisplayName','Channel 1')
the second is to return a handle from each plot call:
C1h = plot(Ch1(1,4:end), 'g', 'DisplayName','Channel 1');
and then in the legend call, provide only one element for each plot:
figure
Ch1h = plot(rand(10,2),'g','DisplayName','First Line');
hold on
Ch2h = plot(rand(10,2),'m','DisplayName','Second Line');
hold off
legend([Ch1h(1),Ch2h(1)], 'Location','best')
I cannot write exact cold without your data, however one of these approaches should work.
.
  2 commentaires
Macarena Santillan
Macarena Santillan le 9 Fév 2022
The function handles worked! Thank you (:
Star Strider
Star Strider le 9 Fév 2022
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (1)

Voss
Voss le 9 Fév 2022
Could be because each call to plot() creates 2 lines. Check it out:
plot(magic(2),'b','DisplayName','Magic');
legend()
You can avoid this by returning the line objects from plot() and making the legend based on only the first one from each call to plot().
h = plot(magic(2),'b','DisplayName','Magic');
legend(h(1));
Or, in a situation more similar to your own:
h = [];
new_h = plot(magic(2),'g','DisplayName','Magic 1');
h(end+1) = new_h(1);
hold on
new_h = plot(magic(2)-1,'m','DisplayName','Magic 2');
h(end+1) = new_h(1);
new_h = plot(magic(2)+1,'r','DisplayName','Magic 3');
h(end+1) = new_h(1);
new_h = plot(inv(magic(2)),'b','DisplayName','Magic 4');
h(end+1) = new_h(1);
legend(h);

Community Treasure Hunt

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

Start Hunting!

Translated by