【问题标题】:Get legend right with stacked bar plot使用堆积条形图获取图例
【发布时间】:2019-05-13 11:33:36
【问题描述】:

我想生成一个包含两条线(plotstairs)和条形(bar)的图。对于plotstairs,我通常使用'DisplayName' 属性来生成图例。使用堆叠的bar 情节,这似乎不再起作用。考虑一下这个 MWE:

x_max = 20;
results = [3 37 50; 7 27 25; 11 0 13; 18 45 0];
figure('Position', [470 430 1000 600]);
plot(0:x_max, polyval([3 1], 0:x_max), 'DisplayName', 'Production rate');
hold on; grid on;
bh = bar(results(:,1), results(:,2:3), 0.2, 'stacked', 'DisplayName', 'Fraction');
xlim([0 x_max]);
legend('Location', 'best');
set(gca, 'FontSize', 18);
hold off

这会产生这个情节:

我想为这两个分数中的每一个获取一个自定义图例条目,例如,'Fraction1', 'Fraction2'。但是,这两种变体都会产生错误:

bar(results(:,1), results(:,2:3), 0.2, 'stacked', 'DisplayName', 'Fraction1', 'Fraction2')
bar(results(:,1), results(:,2:3), 0.2, 'stacked', 'DisplayName', {'Fraction1', 'Fraction2'})

>>Error setting property 'DisplayName' of class 'Bar':
Value must be a character vector or string scalar.

如果我这样做了

bh.get('DisplayName')

我明白了

ans =

  2×1 cell array

    {'getcolumn(Fraction,1)'}
    {'getcolumn(Fraction,2)'}

这意味着 Matlab 内部确实为'DisplayName' 生成了一个单元数组,但不允许我分配一个。这失败了:

bh.set('DisplayName', {'Fraction1'; 'Fraction2'})

我知道我可以直接编辑图例条目的元胞数组,但我更喜欢'DisplayName',因为当我更改绘图命令(或添加或删除其中任何一个)时,图例条目永远不会乱序。有什么解决办法吗?

【问题讨论】:

    标签: matlab plot


    【解决方案1】:

    作为一种快速解决方法,您可以在创建后设置每个条形对象的DisplayName。 请参阅基于您的示例的此解决方案:

    您遇到的问题是堆叠的 bar 创建了一个 Bar 数组(在本例中为 1x2)。你不能设置Bar数组的DisplayName属性,你需要设置每个Bar的属性数组中。

    % Your example code, without trying to set bar display names
    x_max = 20;
    results = [3 37 50; 7 27 25; 11 0 13; 18 45 0];
    figure('Position', [470 430 1000 600]);
    plot(0:x_max, polyval([3 1], 0:x_max), 'DisplayName', 'Production rate');
    hold on; grid on;
    bh = bar(results(:,1), results(:,2:3), 0.2, 'stacked');
    xlim([0 x_max]);
    legend('Location', 'best');
    set(gca, 'FontSize', 18);
    hold off
    
    % Set bar names
    names = {'Fraction1'; 'Fraction2'};
    for n = 1:numel(names)
        set( bh(n), 'DisplayName', names{n} );
    end
    

    您可以在没有循环的情况下执行此操作,代价是语法稍微不那么明确:

    names = {'Fraction1'; 'Fraction2'};
    [bh(:).DisplayName] = names{:};
    

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2013-09-12
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 2014-02-09
      • 2017-11-02
      相关资源
      最近更新 更多