Problem with legend in a plot

7 次查看(过去 30 天)
m m
m m 2015-11-25
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