4

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

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

但是,将来,我可能会在图表上显示超过 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) ; 

在这里需要帮助:

legend(a+0*b,a+1*b,a+2*b, ...., a+N_FILES*b)
4

5 回答 5

7

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
于 2011-04-07T00:51:40.580 回答
6

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

legend('-DynamicLegend');

我的代码如下所示:

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

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

于 2013-05-27T01:22:25.520 回答
5

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

legend_fcn = @(n)sprintf('%0.2f',a+b*n);
legend(cellfun(legend_fcn, num2cell(0:N_FILES) , 'UniformOutput', false));
于 2011-04-07T00:34:48.767 回答
1

最简单的方法可能是创建一个数字列向量用作标签,N_FILES使用函数NUM2STR将它们转换为带有行的格式化字符数组,然后将其作为单个参数传递给LEGEND

legend(num2str(a+b.*(0:N_FILES-1).','%.2f'));
于 2011-04-07T17:56:21.050 回答
0

我通过谷歌找到了这个:

legend(string_matrix)添加一个包含矩阵行string_matrix作为标签的图例。这与legend(string_matrix(1,:),string_matrix(2,:),...).

所以基本上,看起来你可以以某种方式构造一个矩阵来做到这一点。

一个例子:

strmatrix = ['a';'b';'c';'d'];

x = linspace(0,10,11);
ya = x;
yb = x+1;
yc = x+2;
yd = x+3;

figure()
plot(x,ya,x,yb,x,yc,x,yd)
legend(strmatrix)
于 2011-04-07T00:35:59.837 回答