簡體   English   中英

在Matlab中繪制多行的圖例

[英]Legend for multiple lines in Matlab plot

我在繪圖上有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)

作為構建圖例的替代方法,您還可以設置線條的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

使用'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/

legend也可以將字符串的單元格列表作為參數。 嘗試這個:

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

最簡單的方法可能是創建要用作標簽的數字的列向量,使用函數NUM2STR將它們轉換為帶有N_FILES行的格式化字符數組,然后將其作為單個參數傳遞給LEGEND

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

我發現這是我通過谷歌找到的:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM