问题
I want to have multiple legends on one plot. This solution works perfectly before 2014b version. I am trying to figure out how to make this elegantly using handles, but so far no success. Any ideas are welcome.
Example in 2013b:
x = 1:50;
y1 = sin(x/2);
y2 = cos(x/2);
f = figure(1);
pl(1) = plot(x,y1,'g');hold on;
pl(2) = plot(x,y2,'r');
h1 = legend('eg1','eg2');
set(h1,'Location','NorthEast')
tmp = copyobj(h1,f);
h2 = legend(pl,'sin','line');
set(h2,'Location','SouthWest')
I do get something using
ax = gca;
tmp = copyobj([h1,ax],f);
but when I set the legend again, previous legend goes under the plot.
Thanks!
回答1:
Matlab by default only allows one legend per axes, so what you would have to do is create a fake/empty secondary axis in order to get your legend. Mathworks help has a good example of this
Code to produce the below chart is here
x= 0:0.01:2*pi;
y = sin(x);
hl1 = line(x, y,'Color','k','LineStyle','--');
ax1 = gca;
set(ax1,'xlim',[0, 7],'ylim',[-1,
1],'XColor','k','YColor','k');
legend_handle1 = legend(' sin');
ax2 = axes('Position',get(ax1,'Position'),...
'xlim',[0, 7],'ylim',[-1,1],...
'Visible','off','Color','none');
hl2 = line(pi/2, 1,'Color','r','Marker', 'o','Parent',ax2);
hl3 = line(pi, 0,'Color','g','Marker', 'x','Parent',ax2);
legend_handle2 = legend('peak', 'zero');
set(legend_handle2, 'Color', 'none');
回答2:
Here is a simple alternative approach
t = linspace(0,2*pi,200);
frequencies=1:3;
for w=frequencies;
y = sin(w*t);
plot(t,y)
hold on
end
legend("w = " + num2str(frequencies'));
来源:https://stackoverflow.com/questions/38898476/matlab-multiple-legends-on-one-plot-2014b