Home > database >  Matlab legend in loop
Matlab legend in loop

Time:12-13

I have a script that loads several csv's and plots them in a loop (this code sample excluded for brevity) but I'm having trouble labelling the data with the legend. I have tried this:

        if var1() - 1 == 0 
          lgd = legend([txttitle],'interpreter','none');
        else 
          lgd = legend(lgd,[txttitle],'interpreter','none');
          title(lgd,'My Legend Title')
        end

which works for the first csv, but then only plots the second file with the legend (name?) "data1" anymore and gives this error:

Error using legend (line 184)
Handle inputs of type Legend cannot be used with this function.

Error in scriptname (line 27)
                lgd = legend(lgd,[txttitle],'interpreter','none');

If I comment out the else statement and line below it plots all the data but only labels the first plot with the appropriate name, but the rest get labelled data1, data2 etc. So I think it's a syntax problem I just can't quite figure it out

Note: [txttitle] is the name of the datafile and therefore what I want the legend to say.

CodePudding user response:

It's typically easier in these cases to use the DisplayName property of plot (and most plotting functions) and then call legend a single time before/after the loop. For example:

N = 3; % number of lines
data = sort( rand( 10, N ) ); % some random data

% Create figure and hold on for multiple plots
figure(); hold on;
% Loop over the data and plot
for ii = 1:N
   % Generate the name somehow
   txttitle = sprintf( 'Line Number %d', ii );
   % Plot with display name
   plot( data(:,ii), 'DisplayName', txttitle );
end
% Show the legend
legend( 'show', 'interpreter', 'none', 'location', 'best' );

Output:

plot

  • Related