【问题标题】:MATLAB Plot - Legend entry for multiple data rows - getcolumnMATLAB Plot - 多个数据行的图例条目 - getcolumn
【发布时间】:2018-01-13 12:07:49
【问题描述】:

考虑以下示例:

x = magic(3);
figure(1); clf(1);
plot( x, '-r', 'DisplayName', 'Magic' );
legend( 'show' );

MATLAB R2014a 中生成的图例条目是
getcolumn(Magic,1)
getcolumn(Magic,2)
getcolumn(Magic,3)

问题源于legend.m 中的function [leg,labelhandles,outH,outM] = legend(varargin)Copyright 1984-2012 The MathWorks, Inc.)第 628 行:
str{k} = get(ch(k),'DisplayName');
更具体地说,函数get

  • 前置getcolumn(
  • 附加, <Column Number>)

对于以DisplayName 命名的多个具有相同视觉属性的数据行,是否有一种简单的方法可以只显示一个图例条目(或多个,但没有前置和附加的字符串)?

当然,另一种选择是通过绘图句柄(见下文)以编程方式创建多个(或一个)图例条目,但我想保持简短。

一个条目:

x = magic(3);
figure(1); clf(1);
h = plot( x, '-r' );
legend( h(1), 'Magic' );

多个条目:

x = magic(3);
figure(1); clf(1);
h = plot( x, '-r' );
strL = cell( 1, numel(h) );
for k = 1:numel(h)
    strL{k} = sprintf( 'Magic %d', k );
end
legend( h, strL );

在 MATLAB R2014b 中,第一个代码示例不再出现 getcolumn(Name,Row) 的问题。

【问题讨论】:

    标签: matlab matlab-figure legend


    【解决方案1】:

    如果您想以短语法为图例条目设置多个显示名称,您只需准备一个带有它们的元胞数组,假设它称为leg_names,然后使用set 将它们应用于所有一次:

    set(p,{'DisplayName'},leg_names);
    

    我们来看一个例子:

    x = magic(3); % your data
    p = plot( x,'-r'); % plot and get an array of handles to the lines
    % create a list of the desired names for the legend entries:
    leg_names = [repmat('Magic ',size(x,2),1) num2str((1:size(x,2)).')];
    set(p,{'DisplayName'},cellstr(leg_names)); % set all display names
    legend('show'); % show the legend
    

    结果与问题末尾的示例完全相同。

    另外,请注意语法:[lgd,icons,plots,txt] = legend(___) 不推荐使用 (from the docs):

    注意:不推荐使用此语法。它会创建一个不支持所有图形功能的图例。而是使用 lgd = legend(__) 语法返回 Legend 对象并设置 Legend Properties。

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多