Search code examples
matlabmatlab-figure

matlab legend entries from loop don't show up in legend


Commented code does not work, uncommented code works. Why can I not specify which line objects should be included in the legend if the lines where plotted in a loop?

labels = {'1', '2', '3', '4', '5', '6', '7'}
% for i = 1:7
%     [~, I] = min( abs(A - B(i)) );
%     h(i) = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(i,:));
% end
% legend( h, labels, 'Location', 'NorthEast');
[~, I] = min( abs(A - B(1)) );
h1 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(1,:));
[~, I] = min( abs(A - B(2)) );
h2 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(2,:));
[~, I] = min( abs(A - B(3)) );
h3 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(3,:));
[~, I] = min( abs(A - B(4)) );
h4 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(4,:));
[~, I] = min( abs(A - B(5)) );
h5 = plot(T, Z, '-', 'Parent', ax1, 'color', colors(5,:));
[~, I] = min( abs(A - B(6)) );
h6 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(6,:));
[~, I] = min( abs(A - B(7)) );
h7 = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(7,:));
legend([h1, h2, h3, h4, h5, h6, h7], labels, 'Location', 'NorthEast');

Solution

  • legend(target,___) uses the axes or chart(not the handles of line series) specified by target instead of the current axes or chart. Specify the target as the first input argument. You can find more detailed description here. So in your code:

    legend(h,__)
    

    should be

    legend(ax1,__)
    

    or simply

    legend(gca,__)
    

    More generally, there are some solutions more readable& commonly used:

    Solution #1 : specify DisplayName of each line.

    for i = 1:7
     [~, I] = min( abs(A - B(i)) );
     h(i) = plot(T(:,I), Z, '-', 'Parent', ax1, 'color', colors(i,:),'DisplayName',labels{i});end;legend on
    

    Solution #2 : call legend(labels) directly

    labels = {'1', '2', '3', '4', '5', '6', '7'}
    x = 1:100;
    axes(ax1) % specify which axes the next plot should use
    for i = 1:7
        plot(x,rand(size(x)));
        hold on
    end
    hold off
    legend(labels, 'Location', 'NorthEast');