MATLAB graph plotting: assigning legend labels during plot

前端 未结 5 778
傲寒
傲寒 2020-12-29 12:11

I am plotting data in a typical MATLAB scatterplot format. Ordinarily when plotting multiple datasets, I would use the command \'hold on;\', and then plot each of the data,

相关标签:
5条回答
  • 2020-12-29 12:17

    One option is to take advantage of the 'UserData' property like so:

    figure;
    hold on
    plot([0 1], [1 0], '-b', 'userdata', 'blue line')
    plot([1 0], [1 0], '--r', 'userdata', 'red dashes')
    
    % legend(get(get(gca, 'children'), 'userdata'))                      % wrong
    legend(get(gca, 'children'), get(get(gca, 'children'), 'userdata'))  % correct
    

    Edit: As the questioner pointed out, the original version could get out of order. To fix this, specify which handle goes with which label (in the fixed version, it is in the correct order).

    0 讨论(0)
  • 2020-12-29 12:21

    You should be able to set the DisplayName property for each plot:

    figure
    hold on
    plot(...,'DisplayName','DataSet1')
    plot(...,'DisplayName','DataSet2')
    legend(gca,'show')
    

    http://www.mathworks.com/help/matlab/ref/line_props.html

    Side Note: I've found a lot of little tricks like this by getting the figure to look the way I want, then choosing the Figure's "File" menu option "Generate M-File..." and inspecting the generated output code.

    0 讨论(0)
  • 2020-12-29 12:29

    Make a for loop. But Before the for loop, make an array.

    %for example 
    
    legendset = {}
    
    for i = 1:10 
    
    %blabla
    %Then in the fore loop say: 
    
    legendset = [legendset;namedata(i)]
    
    %It puts all names in a column of legendset. 
    %Make sure namedata are characters. 
    
    %foreloop ends
    end
    
    %Then after the foreloop say: 
    
    legend(legendset). 
    
    0 讨论(0)
  • You can try something like the following

    for k = 1:10
    
       h(k) = plot(...);
       name{k} = ['condition ' num2str(k)];
    
    end
    
    legend(h, name);
    
    0 讨论(0)
  • 2020-12-29 12:31

    Use 'DisplayName' as a plot() property, and call your legend as

    legend('-DynamicLegend');
    

    My code looks like this:

    x = 0:h:xmax;                                  %// get an array of x-values
    y = someFunction;                              %// function
    plot(x, y, 'DisplayName', 'Function plot 1');  %// plot with 'DisplayName' property
    
    legend('-DynamicLegend',2);                    %// '-DynamicLegend' legend
    

    Source: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/

    0 讨论(0)
提交回复
热议问题