Problem with legend in a plot
7 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(3 个)
Thorsten
2015-11-25
h(1) = plot(x, sin(x), ':')
hold on
h(2) = plot(x, cos(x), '-')
legend(h, {'sin', 'cos'})
0 个评论
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
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 Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!