Legend colors match with plot

3 Ansichten (letzte 30 Tage)
Rosario Frontino
Rosario Frontino am 3 Apr. 2022
Bearbeitet: the cyclist am 3 Apr. 2022
Hi. I have a for loop in which I plot some curves with different colors.
P=[0.25 0.25 0.2 0.15 0.15];
color = {'r','c','g','y','b','m','k'};
for i=1:numel(P)
plot(1:N,nElemMat(:,i),color{i}); yline(P(i)); hold on;
end
I would like to have a legend in which each color represent the correspondent P(i) (red -> 0.25 , cyan -> 0.25, green -> 0.20,...).
I tried with
legend('0.25', '0.25', '0.2','0.15','0.15');
but colors don't match and I'm not using P.
Do you have any suggestion? Thanks

Akzeptierte Antwort

the cyclist
the cyclist am 3 Apr. 2022
Bearbeitet: the cyclist am 3 Apr. 2022
Here is one way to code this (assuming I understand what you meant):
rng default
N = 3;
P=[0.35 0.25 0.2 0.15 0.10];
nElemMat = rand(N,numel(P));
color = {'r','c','g','y','b','m','k'};
figure
hold on
for i=1:numel(P)
plot(1:N,nElemMat(:,i),color{i})
hy(i) = yline(P(i));
set(hy(i),'Color',color{i})
end
legend(hy,color)
Warning: Ignoring extra legend entries.
The code changes I made were
  • Assign a handle to each yline, so that I could assign the color to each one. (This is the main thing you wanted.)
  • Create the figure explicitly, and execute hold on just once.
  • Define variables that you didn't have in your code, so I had a piece of self-contained code that would run.
  • Changed the values of P, so you see every line
  2 Kommentare
Rosario Frontino
Rosario Frontino am 3 Apr. 2022
Thanks for your answer and the explanation. My main problem is the legend for the plot.
I would like to have a legend in the form (P(i) -> color(i)). Is it possible?
the cyclist
the cyclist am 3 Apr. 2022
Bearbeitet: the cyclist am 3 Apr. 2022
Sorry, I missed the part about a legend.
I've edited the code to show how to use the handles as an input to legend.
Note that the my code here is a bit weird, because I am using the handles to the horizontal lines, not to the plot lines themselves (but you seem to have a one-to-one correspondence, so that is OK). You could also have assigned handles to the plot lines themselves instead:
hp(i) = plot(...)
and assigned a legend based on those. That would be the norm, actually.
Also, I just used the color names themselves as the legend text. Obviously, you don't need to do that.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by