Mismatch legend and plots
Show older comments
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
Answers (1)
Walter Roberson
on 8 Jun 2020
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 Comments
Hg
on 8 Jun 2020
Walter Roberson
on 8 Jun 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
on 8 Jun 2020
Cheuk Yin Wong
on 29 Jun 2022
This also helps with my problem I currently have, thanks. May I ask what is the (1) in h1(1)? Thanks.
Walter Roberson
on 29 Jun 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
on 30 Jun 2022
Thank you very much!
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!