Mismatch legend and plots

I've read a few posts about people having the same issue but i can't fix it myself.
I have different figures and I plot them and add their legends but the color doesn't match with the plots nor does the type of line. I have a marker and the legend displays it as a straight line
figure('Name','Voltaje Inducido Corriente Directa')
hold on
plot(tiempo1(2:end),voltaje_dc_1,'r')
plot(tiempo2,voltaje_dc_2,'ob','markerfacecolor','b')
title("Voltaje Inducido")
xlabel('Tiempo')
ylabel('Voltaje Inducido')
legend('Voltaje Ind corriente directa tiempo 1','Voltaje Ind corriente directa tiempo 2')
hold off
Looks something like this:
my variables "voltaje_dc_1" and "voltaje_dc_2" are arrays of different lenght
voltaje_dc_1 = 299 x 299
voltaje_dc_2 = 1 x 90

Réponses (1)

Walter Roberson
Walter Roberson le 8 Juin 2020

1 vote

When you have a 2D array of Y values, then one output line is created for each column of Y (though sometimes it is for each row instead, of that is what is needed to make it match the number of x elements.)
legend() wants to create a legend for all the lines.
figure('Name','Voltaje Inducido Corriente Directa')
hold on
h1 = plot(tiempo1(2:end),voltaje_dc_1,'r')
h2 = plot(tiempo2,voltaje_dc_2,'ob','markerfacecolor','b')
title("Voltaje Inducido")
xlabel('Tiempo')
ylabel('Voltaje Inducido')
legend([h1(1), h2(1)], {'Voltaje Ind corriente directa tiempo 1','Voltaje Ind corriente directa tiempo 2'})
hold off

6 commentaires

Hg
Hg le 8 Juin 2020
Thank you very much. It worked right away!
For what I see you defined variables "h1" and "h2" for the plots and then for the legend you assigned them the labels just to the first element of each of the arrays?
Walter Roberson
Walter Roberson le 8 Juin 2020
Yes, exactly. h1 at least will be a vector of line object handles, and you want to select one representative one of them to insert into the legend.
Hg
Hg le 8 Juin 2020
Got it! Thanks again
Cheuk Yin Wong
Cheuk Yin Wong le 29 Juin 2022
This also helps with my problem I currently have, thanks. May I ask what is the (1) in h1(1)? Thanks.
Walter Roberson
Walter Roberson le 29 Juin 2022
When you have a 2D array of Y values, then one output line is created for each column of Y. One handle is returned for each of those lines. The (1) narrows it down to the first of the handles.
In the case of this example, h1(1) would be the handle to the line for the first column of voltaje_dc_1
Cheuk Yin Wong
Cheuk Yin Wong le 30 Juin 2022
Thank you very much!

Connectez-vous pour commenter.

Tags

Question posée :

Hg
le 8 Juin 2020

Commenté :

le 30 Juin 2022

Community Treasure Hunt

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

Start Hunting!

Translated by