![temp0.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/223997/temp0.png)
Why doesn't legend distinguish colors?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
dcydhb dcydhb
el 12 de Jun. de 2019
Comentada: dcydhb dcydhb
el 12 de Jun. de 2019
when plotting the figures, figure 1 Legend distinguishes colors and the figure 2 legend doesn't,why?
codes are as this
clc;
clear all;
close all;
t=0:0.1:50;
ca=1;
t0=3.5;
omega=2*pi/t0;
ca2=abs(2*sin(omega/2*t));
a0=1;
ca3=1+a0*sin(omega*t);
figure(1)
plot(t,ca,'r')
hold on
plot(t,ca2,'g')
hold on
plot(t,ca3,'b')
legend('ca=1','ca=abs(2*sin(omega/2*t))','ca=1+0.5*sin(omega*t)');
ylim([-5,5])
figure(2)
x = -pi:pi/20:pi;
plot(x,cos(x),'r',x,sin(x),'b')
hleg1 = legend('cos_x','sin_x');
![figure1.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/223993/figure1.png)
![figure2.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/223994/figure2.png)
0 comentarios
Respuesta aceptada
Stephen23
el 12 de Jun. de 2019
Editada: Stephen23
el 12 de Jun. de 2019
The problem occurs on this line:
plot(t,ca,'r')
Because t is a vector (with 501 elements) and ca is a scalar, then you are telling MATLAB to create 501 separate plotted points, each colored red (and so the legend is showing you the labels for the first three of those points!). This is clearly explained in the plot documentation: "If one of X or Y is a scalar and the other is either a scalar or a vector, then the plot function plots discrete points."
The solution is simple: ensure that you plot two vectors of the same size, e.g.:
plot(t,ca*ones(size(t)),'r')
giving:
![temp0.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/223997/temp0.png)
Más respuestas (1)
Bjorn Gustavsson
el 12 de Jun. de 2019
When I intend to use legend I always take care of having the handles to the plotted objects available for the legend call:
ph1 = plot(randn(1,12));
hold on
ph2 = plot(sin(1:12));
legend([ph1,ph2],'1','2')
That way you have better controll over what to put into the legend, in what order, also it allows better controll over the
plotted objects - it becomes much simlper to change linestyles, colours and such if that's needed for clarity.
The answer to your question: What happened is that you plot a constant, ca1 (scalar value of 1) at a number of times. This generates a numel(t) line-handles which all have red colour, then you add a blue and a green line which will be items 502 and 503 in the handle-graphics list...
Ver también
Categorías
Más información sobre Legend en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!