Legend for yyaxis at two different locations

35 次查看(过去 30 天)
I have a figure created with plotyy. I want to place legends near to their respective axes , i.e., at northeast for left y-axis and at northwest for right y-axis. The following set of commands just places the last legend command. Please, help.
n=-180:180;
x=(pi/180).*n;
y=sin(x);
y2=sin(x).*cos(x);
y3=cos(x);
[ax h1 h2]=plotyy(n,y,n,y2)
h3=line(n,y3,'Color','r','LineWidth',2,'Parent',ax(1))
set(h1,'Color','k','LineStyle','-','LineWidth',1.0);
set(h2,'Color','b','LineStyle','-','LineWidth',1.5);
legend(ax(1),{'h1','h3'},'Location','NorthWest')
legend(ax(2),{'h2'},'Location','NorthEast');

采纳的回答

Adam Danz
Adam Danz 2020-2-27
编辑:Adam Danz 2020-2-27
The second call to legend() is replacing the first legend (you can only have 1 legend).
I reworked your code to use yyaxis instead of plotyy.
Solution 1: use 1 legend
This solution puts all handles into the same legend. See inline comments for details.
n=-180:180;
x=(pi/180).*n;
y=sin(x);
y2=sin(x).*cos(x);
y3=cos(x);
% Plot on left axis
yyaxis left
h1 = plot(n,y, '-k', 'LineWidth', 1, 'DisplayName', 'h1');
set(gca, 'YColor', 'k') % set y axis color to same as line color
hold on
h3=line(n,y3,'Color','r','LineWidth',2, 'DisplayName', 'h3');
% Plot on right axis
yyaxis right
h2 = plot(n,y2, '-b', 'LineWidth', 1.5, 'DisplayName', 'h2');
set(gca, 'YColor', 'b') % set y axis color to same as line color
Solution 2: kludge in a 2nd legend
Since you can only have 1 legend per axis, this solution produces a second invisible axis and copies the h2 object to the invisible axis so that it can have its own legend. See inline comments for details.
n=-180:180;
x=(pi/180).*n;
y=sin(x);
y2=sin(x).*cos(x);
y3=cos(x);
% Plot on left axis
yyaxis left
h1 = plot(n,y, '-k', 'LineWidth', 1, 'DisplayName', 'h1');
set(gca, 'YColor', 'k') % set y axis color to same as line color
hold on
h3=line(n,y3,'Color','r','LineWidth',2, 'DisplayName', 'h3');
% Plot on right axis
yyaxis right
h2 = plot(n,y2, '-b', 'LineWidth', 1.5, 'DisplayName', 'h2');
set(gca, 'YColor', 'b') % set y axis color to same as line color
% Produce left-axis legend
legend([h1,h3], 'Location', 'NorthWest')
% Create invisible axis in the same position as the current axes
ax = gca(); % Handle to the main axes
axisCopy = axes('Position', ax.Position, 'Visible', 'off');
% Copy objects to second axes
hCopy = copyobj(h2, axisCopy);
% Replace all x values with NaN so the line doesn't appear
hCopy.XData = nan(size(hCopy.XData));
% Create right axis legend
legend(hCopy, 'Location', 'NorthEast')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Two y-axis 的更多信息

产品


版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by