2011-04-07 125 views
4

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

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) 
+2

为什么你不只是做'X = 1:则n_frames;'?我认为更清晰。其实你根本不需要x,'plot(phi_matrix);'应该工作。 – yuk 2011-04-07 02:02:47

+0

@yuk:这样会更好,但是他们必须调换'phi_matrix',以便将每列作为一条线绘制。 – gnovice 2011-04-07 17:48:11

回答

5

legend也可以采取的字符串作为参数的小区列表。试试这个:

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

我发现我this通过谷歌发现:

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) 
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 
1

最简单的方法可能是创建为您的标签使用数量的列向量,将它们转换成一个格式化字符数组使用N_FILES行功能NUM2STR,然后通过这个作为一个参数来LEGEND

legend(num2str(a+b.*(0:N_FILES-1).','%.2f')); 
6

使用“显示名称”作为剧情()属性,并调用你的传奇为

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/