在 MATLAB 中的单个图形上创建 2 个图例框?

Creating 2 legend boxes on a single graph in MATLAB?

我正在尝试创建一个带有 2 个图例框的图表,但我第一次调用图例函数时它忽略了那个,只创建了第二个。我不确定我做错了什么或如何解决这个问题。

这是我的代码:

% Plotting graphs on the same x with different y
yyaxis left
plot(x, y3)
xlabel('x (between 0 and 2\pi)')
ylabel('2sin(x)cos(x)')
legend('2sin(x)cos(x)', "Location", "NorthWest")


yyaxis right
plot(x, y4)
ylabel('sin(x)cos(x)')
legend('sin(x)/cos(x)', "Location", "NortEast")

这给出了以下输出:

如您所见,这甚至不是图表的正确图例。黑色应该是2sin(x)cos(x).

顺便说下我用的是MATLAB R2020b

这里有一个代码示例可以回答您的问题...

% just some "data"
x=0:0.01:2*pi;
y3=sin(x);
y4=cos(x);


yyaxis left
h3=plot(x, y3,'DisplayName', 'text 1')

yyaxis right
h4=plot(x, y4,'DisplayName', 'text 2')

% Produce left-axis legend
legend(h4 , 'Location', 'NorthWest')
% Create invisible axis in the same position as the current axes
h = gca(); % Handle to the main axes

% Copy objects to second axes
hc = copyobj(h3, axes('Position', h.Position, 'Visible', 'off')); 
% Replace all x values with NaN so the line doesn't appear
hc.XData = nan(size(hc.XData)); 
% Create right axis legend
legend(hc, 'Location', 'NorthEast')