在Matlab中绘制多行的图例

Flo*_*ora 4 matlab legend

我在绘图上有13行,每行对应一个文本文件中的一组数据.我想标记每行从第一组数据开始为1.2,然后是1.25,1.30,到1.80等,每个增量为0.05.如果我要手动输入,那就是

legend('1.20','1.25','1.30', ...., '1.80')
Run Code Online (Sandbox Code Playgroud)

但是,在将来,我可能在图表上有超过20行.因此输入每一个都是不现实的.我尝试在图例中创建一个循环,它不起作用.

我怎样才能以实用的方式做到这一点?


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) ; 
Run Code Online (Sandbox Code Playgroud)

需要帮助:

legend(a+0*b,a+1*b,a+2*b, ...., a+N_FILES*b)
Run Code Online (Sandbox Code Playgroud)

Jon*_*nas 7

作为构建图例的替代方法,您还可以设置DisplayName线条的属性,以便图例自动更正.

因此,您可以执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)


小智 6

使用'DisplayName'作为plot()属性,并将您的图例称为

legend('-DynamicLegend');
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

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


nib*_*bot 5

legend也可以将字符串的单元格列表作为参数.试试这个:

legend_fcn = @(n)sprintf('%0.2f',a+b*n);
legend(cellfun(legend_fcn, num2cell(0:N_FILES) , 'UniformOutput', false));
Run Code Online (Sandbox Code Playgroud)