【发布时间】:2019-05-13 11:33:36
【问题描述】:
我想生成一个包含两条线(plot、stairs)和条形(bar)的图。对于plot 和stairs,我通常使用'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',因为当我更改绘图命令(或添加或删除其中任何一个)时,图例条目永远不会乱序。有什么解决办法吗?
【问题讨论】: