Matlab绘图中多条曲线的图例

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)

2
为什么不直接写成 x=1:N_FRAMES; 呢?我认为这样更清晰。实际上你根本不需要 x,直接写 plot(phi_matrix); 就可以了。 - yuk
@yuk:这样会更好,但是他们需要转置phi_matrix,以便将每个列绘制为一条线。 - gnovice
5个回答

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

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/

在Matlab中,图例是一种用于标识不同曲线或数据系列的工具。虽然它们非常有用,但是Matlab文档并没有提供所有可用选项的完整列表。本文介绍了一些不太为人知的图例选项和技巧。


5

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

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

1

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

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

0

我通过 Google 找到了 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接