Problem with legend in a plot

조회 수: 12 (최근 30일)
m m
m m 2015년 11월 25일
댓글: Mike Garrity 2015년 12월 1일
Hey.
I have some problems using legend in a plot. I have 2 plots where the first one has dots and the second one is a line plot. When I use legend it somehow shows dots for both plots when it has to show dots for the first plot and a line for the second.
Can anyone help me with this?
I have written the following:
Legend = cell(2,1);
Legend{1} = 'Plot1';
Legend{2} = 'Plot2';
legend(Legend{:});
Thank you!

답변 (3개)

Thorsten
Thorsten 2015년 11월 25일
h(1) = plot(x, sin(x), ':')
hold on
h(2) = plot(x, cos(x), '-')
legend(h, {'sin', 'cos'})

m m
m m 2015년 11월 25일
편집: m m 2015년 11월 25일
I have the second plot(plot2) in an if-statement:
if max(size(A)) ~= 1
plot2 = plot(x,A,'r-');
end

PChoppala
PChoppala 2015년 12월 1일
An example (although there are better ways of doing it),
n=50;
x=linspace(1/n,1,n);
y1=sin(4*pi*x);
y2=cos(4*pi*x(10:30)); % for example
figure
plot(x,y1,'b.','markersize',10)
grid on
if numel(y2)>1,
hold on
plot(x(10:30),y2,'color',[1 0 0],'linewidth',1.5)
legend('sine','cosine')
else
legend('sine')
end
  댓글 수: 1
Mike Garrity
Mike Garrity 2015년 12월 1일
Yes, or another option would be the following:
n=50;
x=linspace(1/n,1,n);
y1=sin(4*pi*x);
y2=cos(4*pi*x(10:30)); % for example
figure
plot(x,y1,'b.','MarkerSize',10,'DisplayName','sine')
grid on
if numel(y2)>1
hold on
plot(x(10:30),y2,'Color',[1 0 0], ...
'LineWidth',1.5,'DisplayName','cosine')
end
legend show
The 'legend show' will pick up the strings from the DisplayName properties of the objects it finds in the axes. This can be useful if you have a large number of plots and complex conditionals.

댓글을 달려면 로그인하십시오.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by