MATLAB: How to place a legend on a plot produced from the PLOTYY command in MATLAB 7.5 (R2007b)

axislegendMATLABmultipleplotyy

For example, if I execute the following commands, the legend only contains one line and the figure contains only one line:
x = 1:10;
y = 10:-1:1;
[ax,h1,h2] = plotyy(x,x,x,y);
[legh, objh] = legend('str1', 'str2');

Best Answer

This enhancement has been incorporated in Release 2008a (R2008a). For previous product releases, read below for possible workarounds:
The PLOTYY command creates two axes. In the first axes it plots the first (x1,y1) data set and in the second axes it plots the second (x2,y2) data set.
With the code above, two axes are created and two lines are plotted. The first axes has a white color and the second axes has a color of 'none'. This allows you to see the line drawn in the first axes. When the LEGEND command is executed it obtains the line information from the current axes which contains only one line. Therefore, the resulting legend only shows one line.
To create a plotyy figure with a legend, try the following:
% Create the plotyy figure. The handle to the first line is h1 and the handle
% to the second line is h2.
x = 1:10;
y = 10:-1:1;
[ax,h1,h2] = plotyy(x,x,x,y);
% Make the second axes current (the axes with a color of 'none') so that both lines
% are visible
axes(ax(2))
%Create the legend and explicitly state the handles to each line
[legh, objh] = legend([h1 h2],'str1', 'str2');