Hide legend entries with addaxis function

3 views (last 30 days)
Hello,
I am plotting using the addaxis function (reference addaxis) and am having trouble with my legend display. I would like to hide certain plots from the legend, but when I end up trying to do this, the legend line seems to display incorrectly: the legend entry for the the addaxis entry won't display the corresponding line. See below for the example code and output. Does anyone have any suggestions to help display the 'y2' line in the legend while keeping the 'y_compare' hidden?
-----------
x1 = 0:.1:2*pi;
y1 = sin(x1);
x1_compare = 0:.05:(2*pi);
y1_compare = (sin(x1_compare))-.1;
xmin = x1;
ymin = y1-1;
xmax = x1;
ymax = y1+1.5;
x2 = x1;
y2 = .5*cos(x2);
hold on
h_compare = plot(x1_compare, y1_compare, 'color',[0.6 0.6 0.6]);
h_1 = plot(x1,y1,'rx', xmin, ymin,'m--', xmax, ymax, 'm:');
h_2 = addaxis(x2,y2, 'b');
xlabel('x-axis');
addaxislabel(1,'y-axis 1'); addaxislabel(2,'y-axis 2');
%legend('show')
legend([h_1' h_2], 'y1', 'ymin', 'ymax', 'y2')
hold off
----------

Accepted Answer

Geoff Hayes
Geoff Hayes on 9 Oct 2014
Edward - addaxis returns a handle to the axes, and not the line that was drawn on that axes. Since there is only one line drawn on that axes, h_2, we can use the Children property of the axes to get that handle to the line/curve. Try modifying your code as
h_2 = addaxis(x2,y2, 'b');
% get child line
h_2_child = get(h_2,'Children');
and then change the legend call to
legend([h_1' h_2_child], 'y1', 'ymin', 'ymax', 'y2')
Now, in the legend, the y2 curve will show with a blue line next to it.

More Answers (1)

Edward
Edward on 9 Oct 2014
Geoff,
That worked great! Thank you!

Community Treasure Hunt

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

Start Hunting!