Plot multiple errorbars in pairs

23 ビュー (過去 30 日間)
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2019 年 9 月 24 日
編集済み: Adam Danz 2021 年 12 月 10 日
Hi again,
I have plotted some errorbars using the commands you suggested in my previous question:
x=1; y=8.35;
sd=4.13;
bar(x,y);
hold on
errorbar(x,y,sd)
ylim([0 14])
xticks([0:2])
hold off
However, I am trying to do the same with a pair of graphs, so in each number there are two bars instead of 1. I modified the code like this:
error=[3.3 2.1;1.1 4];
x=[1:2 ;1:2]';
y=[3.5 2.2; 5.2 3.3];
bar(x,y)
hold on
errorbar(x,y,error,'*')
ylim([-8 18])
xticks([1:2])
hold off
The problem is that the error bars which show the deviation don't fit exactly at the barcharts. Do you know how to fix this?
I have attached a screenshot

採用された回答

Adam Danz
Adam Danz 2019 年 9 月 24 日
編集済み: Adam Danz 2021 年 12 月 10 日
To locate the center of each grouped bar in Matlab releases prior to R2019b, use the undocumented bar object property, "XOffset" which is the horizontal offset of each bar-center from the group index value. In R2019b and later, use XEndpoints.
xCnt are the bar centers.
error=[3.3 2.1;1.1 4];
x=[1:2 ;1:2]';
y=[3.5 2.2; 5.2 3.3];
h = bar(x,y)
hold on
% Get bar centers
xCnt = h(1).XData.' + [h.XOffset];
% Alternative: xCnt = get(h(1),'XData').' + cell2mat(get(h,'XOffset')).'; % XOffset is undocumented
% In Matlab R2019b and later,
% xCnt = vertcat(h.XEndPoints)';
errorbar(xCnt(:),y(:),error(:),'*') % <--- If you want 1 errorbar object
% errorbar(xCnt,y,error,'*') % <--- If you want separate errorbar objects, 1 for each bar-group
% errorbar(...,'k*') to make the errorbars black (which is better than yellow)
ylim([-8 18])
xticks([1:2])
hold off
  2 件のコメント
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2019 年 9 月 24 日
thanks a lot!!!
Adam Danz
Adam Danz 2019 年 9 月 24 日
Glad I could help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeErrorbars についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by