2011-04-07 126 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/