I am trying to create a chart with 2 legend boxes but the first time I call the legend function it disregards that and only creates the second one. I'm not sure what I am doing wrong or how to fix this.
Here is my code:
% 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")
This gives the following output:
Which as you can see is not even the right legend for the graph. Black is supposed to be 2sin(x)cos(x).
I am using MATLAB R2020b by the way.
here's a code sample that will answer your question...
% 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')