Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 2pi)')
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:

I think I have to link it like this because I am new to stackoverflow, sorry

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...