微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在分组条中绘制误差条?

如何解决如何在分组条中绘制误差条?

我想在分组条中绘制误差条。我写了以下代码

x = categorical({'a','b','c','d','e'});
y = [6816,7215; 5824,6180; 4860,5200; 3860,4206; 2838,3185];
errlow = [238,337;270,355;303,297;291,340;259,382];
errhigh = [231,264;225,337;153,171;185,286;167,247];

b = bar(x,y);

hold on

xtips1 = b(1).XEndPoints;
ytips1 = b(1).YEndPoints;

er = errorbar(xtips1,ytips1,errlow(:,1),errhigh(:,1));    
er.Color = [0 0 0];                            
er.Linestyle = 'none';

hold on

xtips2 = b(2).XEndPoints;
ytips2 = b(2).YEndPoints;

er2 = errorbar(xtips2,ytips2,2),2));    
er2.Color = [0 0 0];                            
er2.Linestyle = 'none';

hold off

ylim([2400 7600]);

误差线显示在图表中。请看,如图所示,它们直接在 a、b、c、d 和 e 上方,但不在栏上。

enter image description here

我希望它们在相关的条上('绿色'标记错误应该在右边的条上,而'红色'标记错误应该在左边的条上),如图所示。我该怎么做?

提前致谢!

解决方法

这是 MathWorks Support Team 提供的答案,发布于 MATLAB Answers(除了一些小的修改)。


指定 errorbar 函数应在补丁内显示误差线的功能在 MATLAB 中不可用。 此限制有两种变通方法,其用法取决于您使用的 MATLAB 版本。

  1. 如果您使用的是 R2019a 或更早版本,请找到每个条形的中心并将此数据与相应的错误值一起传递到 errorbar
  2. 如果您使用的是 R2019b 或更高版本,请使用 XEndPoints 属性和 pass this data into errorbar 检索每个条形的 x 坐标。

以下是上述示例:

% Example data
model_series = [10 40 50 60; 20 50 60 70; 30 60 80 90];
model_error = [1 4 8 6; 2 5 9 12; 3 6 10 13];
b = bar(model_series,'grouped');

对于 MATLAB R2019a 或更早版本:

hold on
% Find the number of groups and the number of bars in each group
ngroups = size(model_series,1);
nbars = size(model_series,2);
% Calculate the width for each bar group
groupwidth = min(0.8,nbars/(nbars + 1.5));
% Set the position of each error bar in the centre of the main bar
% Based on barweb.m by Bolu Ajiboye from MATLAB File Exchange
for i = 1:nbars
    % Calculate center of each bar
    x = (1:ngroups) - groupwidth/2 + (2*i-1) * groupwidth / (2*nbars);
    errorbar(x,model_series(:,i),model_error(:,'k','linestyle','none');
end
hold off

对于 MATLAB 2019b 或更高版本:

hold on
% Calculate the number of bars in each group
nbars = size(model_series,2);
% Get the x coordinate of the bars
x = [];
for i = 1:nbars
    x = [x ; b(i).XEndPoints];
end
% Plot the errorbars
errorbar(x',model_series,model_error,'none')'
hold off

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。