Problem with legend in a plot

12 visualizzazioni (ultimi 30 giorni)
m m
m m il 25 Nov 2015
Commentato: Mike Garrity il 1 Dic 2015
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!

Risposte (3)

Thorsten
Thorsten il 25 Nov 2015
h(1) = plot(x, sin(x), ':')
hold on
h(2) = plot(x, cos(x), '-')
legend(h, {'sin', 'cos'})

m m
m m il 25 Nov 2015
Modificato: m m il 25 Nov 2015
I have the second plot(plot2) in an if-statement:
if max(size(A)) ~= 1
plot2 = plot(x,A,'r-');
end

PChoppala
PChoppala il 1 Dic 2015
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 Commento
Mike Garrity
Mike Garrity il 1 Dic 2015
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.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by