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 Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by