Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend for multiple lines in Matlab plot

Tags:

legend

matlab

I have 13 lines on a plot, each line corresponding to a set of data from a text file. I'd like to label each line starting with the first set of data as 1.2, then subsequently 1.25, 1.30, to 1.80, etc., with each increment be 0.05. If I were to type it out manually, it would be

legend('1.20','1.25','1.30', ...., '1.80')

However, in the future, I might have more than 20 lines on the graph. So typing out each one is unrealistic. I tried creating a loop in the legend and it doesn't work.

How can I do this in a practical way?


N_FILES=13 ; 
N_FRAMES=2999 ; 
a=1.20 ;b=0.05 ; 
phi_matrix = zeros(N_FILES,N_FRAMES) ; 
for i=1:N_FILES
    eta=a + (i-1)*b ; 
    fname=sprintf('phi_per_timestep_eta=%3.2f.txt', eta) ; 
    phi_matrix(i,:)=load(fname);
end 
figure(1);
x=linspace(1,N_FRAMES,N_FRAMES) ;
plot(x,phi_matrix) ; 

Need help here:

legend(a+0*b,a+1*b,a+2*b, ...., a+N_FILES*b)
like image 655
Flora Avatar asked Dec 02 '22 03:12

Flora


2 Answers

As an alternative to constructing the legend, you can also set the DisplayName property of a line so that the legend is automatically correct.

Thus, you could do the following:

N_FILES = 13;
N_FRAMES = 2999;
a = 1.20; b = 0.05;

% # create colormap (look for distinguishable_colors on the File Exchange)
% # as an alternative to jet
cmap = jet(N_FILES);

x = linspace(1,N_FRAMES,N_FRAMES);

figure(1)
hold on % # make sure new plots aren't overwriting old ones

for i = 1:N_FILES
    eta = a + (i-1)*b ; 
    fname = sprintf('phi_per_timestep_eta=%3.2f.txt', eta); 
    y = load(fname);

    %# plot the line, choosing the right color and setting the displayName
    plot(x,y,'Color',cmap(i,:),'DisplayName',sprintf('%3.2f',eta));
end 

% # turn on the legend. It automatically has the right names for the curves
legend
like image 51
Jonas Avatar answered Dec 04 '22 13:12

Jonas


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/

like image 28
Will Avatar answered Dec 04 '22 11:12

Will