如何在MATLAB中为单个图添加两个图例?

Wil*_*ill 7 matlab plot legend matlab-figure

我想在MATLAB中为一个情节添加两个图例.我怎样才能做到这一点?

Amr*_*mro 9

您可以创建第二个叠加轴,其中包含自己的图例(当然在不同的位置).


编辑:

这是一个简单的例子:

%# create some plot with a legend
hAx(1) = axes();
hLine(1) = plot(1:10, 'Parent',hAx(1));
set(hAx(1), 'Box','off')
legend(hLine(1), 'line')

%# copy the axis
hAx(2) = copyobj(hAx(1),gcf);
delete( get(hAx(2),'Children') )            %# delete its children
hLine(2) = plot(sin(1:10), 'Color','r', 'Parent',hAx(2));
set(hAx(2), 'Color','none', 'XTick',[], ...
    'YAxisLocation','right', 'Box','off')   %# make it transparent
legend(hLine(2), {'curve'}, 'Location','NorthWest', 'Color','w')
Run Code Online (Sandbox Code Playgroud)

截图


mar*_*sei 5

要创建粘性图例,您可以调用 copyobj

handle_legend = legend(handle_plot, 'string1');
copyobj(handle_legend, handle_figure);
Run Code Online (Sandbox Code Playgroud)

copyobj函数只是在图中保留其关联的图例。

这适用于单个轴(无需创建第二个叠加轴),并且可以通过这种方式添加多个图例。

例子:

%declare figure
hfigure = figure('Color', 'w');

%plot 2 lines (red and blue)
hplot1 = plot(1:10,'r-.x');
hold on;
hplot2 = plot(10:-1:1,'b--o');

%plot legends
hlegend1 = legend(hplot1, 'Data 1', 'Location','East'); %display legend 1
new_handle = copyobj(hlegend1,hfigure);                 %copy legend 1 --> retain
legend(hplot2, 'Data 2', 'Location','West');            %display legend 2
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明