Matlab multiple legends on one plot 2014b

牧云@^-^@ 提交于 2019-12-11 01:14:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!