필터 지우기
필터 지우기

Why doesn't legend distinguish colors?

조회 수: 2 (최근 30일)
dcydhb dcydhb
dcydhb dcydhb 2019년 6월 12일
댓글: dcydhb dcydhb 2019년 6월 12일
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
figure2.png

채택된 답변

Stephen23
Stephen23 2019년 6월 12일
편집: Stephen23 2019년 6월 12일
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

추가 답변 (1개)

Bjorn Gustavsson
Bjorn Gustavsson 2019년 6월 12일
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...

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품


릴리스

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by