Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

Creating 2 legend boxes on a single graph in MATLAB?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...