问题
Here is my code:
N=100;
n=50;
tau=0.001;
h=0.01;
lambda=tau/h;
mu=lambda/2;
u=zeros(N,n);
u1=zeros(N,n);
u2=zeros(N,n);
phi=zeros(n,1);
for i=1:n
for j=1:N
u(j,i)=cos(2*pi*i*(j-1)*h);
u1(j,i)=cos(2*pi*i*((j-1)*h-tau));
end
for j=2:N
u2(j,i)=u(j,i)-lambda*(u(j,i)-u(j-1,i));
end
u2(1)=0;
phi(i,1)=2*pi*i/N;
end
uf=zeros(n,1);
uf1=zeros(n,1);
uf2=zeros(n,1);
for i=1:n
for j=1:N
uf(i,1)=uf(i,1)+(u(j,i)*exp(-1i*(j-1)*phi(i,1)))/100;
uf1(i,1)=uf1(i,1)+u1(j,i)*exp(-1i*j*phi(i,1))/100;
uf2(i,1)=uf2(i,1)+(u2(j,i)*exp(-1i*(j-1)*phi(i,1)))/100;
end
end
final=zeros(n,1);
for i=1:n
final(i,1)=-(h/(1i*tau))*(log(uf2(i)/uf(i)));
end
figure;
hold on
z=1:1:n;
b = real(final(z,1));
%plot(phi(z,1),b,'o');
c = imag(final(z,1));
%plot(phi(z,1),c,'-');
%plot(phi(z,1),0,'-');
plot(phi(z,1),b,'ro',phi(z,1),c,'ko',phi(z,1),0,'k-');
legend('Real','Imaginary');
legend ('Location','NorthWest');
xlabel('Reduced Wavenumber')
ylabel('Modified Wavenumber')
I am plotting a line at y=0 for reference. I do not want them in legend. But I am getting this figure:

回答1:
Instead of plotting everything with one plot
-command, do it like this:
plot(phi(z,1),b,'ro'); hold on
plot(phi(z,1),c,'ro'); hold on
plot(phi(z,1),0,'k-'); hold off
legend('Real','Imaginary','Location','NorthWest');
xlabel('Reduced Wavenumber')
ylabel('Modified Wavenumber')
You shouldn't have problems then.
The actual reason is, that the legend is called differently in this case. The more elegant solution offers the answer of Magla.
回答2:
Legends in matlab should be called like this
plot(phi(z,1),b,'ro',phi(z,1),c,'ko',phi(z,1),0,'k-');
legend( {'Real','Imaginary'} , 'Location', 'NorthWest');
where legend labels are stored in a cell array of strings {...}
. Location
is a parameter to be placed either with the legend call (like in the above code) or outside the function by using the set
function
h = legend({'Real','Imaginary'});
set(h, 'Location','NorthWest');
This gives

来源:https://stackoverflow.com/questions/18895523/what-should-i-do-to-not-show-the-legend-for-all-the-plots