legend for group of lines

后端 未结 6 443
盖世英雄少女心
盖世英雄少女心 2020-12-08 07:46

I like to plot two groups of lines in the same plot. Each group has two lines with same color and I have to draw them in the order of one group after another group. I try to

6条回答
  •  醉话见心
    2020-12-08 08:40

    In response to your update, and to extend Andrew Janke's answer, I found this method to be perfect for an automatic legend:

    % Sample data
    order = -1:2;      % number of orders to plot
    x = (0:0.01:10)';
    
    % Plot each instance of data in a separate graph
    for i=1:numel(order)
        plot(x,besselj(order(i),x))
        hold all
    
        % Amend legend to include new plot
        [~,~,~,current_entries] = legend;
        legend([current_entries {sprintf('Order = %i',order(i))}]);
    end
    

    Gives the following figure: Plot of Bessel functions with automatic legend

    EDIT: In Matlab 2014b, the use of "legend" has changed and the solution(s) above will throw errors. Instead, we should modify the 'String' property of the legend. Follow this code to get the same result as my previous example:

    % Sample data
    order = -1:2;      % number of orders to plot
    x = (0:0.01:10)';
    
    % Plot each instance of data in a separate graph
    for i=1:numel(order)
        plot(x,besselj(order(i),x))
        hold on
    
        % Amend legend 'entries' to include new plot
        entries(i) = { sprintf('Order = %i',order(i)) };
    end
    
    % Create legend using the 'entries' strings
    legend('String',entries);
    

    Now you can add as many plots as you want and the legend will automatically update!

提交回复
热议问题