MATLAB Answers

# How to determine the x-axis positions of the bars in a grouped bar chart

212 ビュー (過去 30 日間)
the cyclist 2015 年 4 月 16 日

Suppose I make the following bar chart:
figure; bar([1 2],[3 4; 5 6])
How can I programatically find the x-axis locations of each of the bars? I don't want x = [1 2]. I want the actual locations of the blue and yellow bars.

#### 0 件のコメント

サインイン to comment.

### 採用された回答

Allison 2015 年 6 月 3 日
the cyclist-
I ran into this same problem when switching from Matlab 2011b to 2015b, with the updated graphics engine. After fooling around for a bit, I found that the following code will work (adapted from your original post):
%
mean_velocity = [5 6 7; 8 9 10]; % mean velocity
std_velocity = randn(2,3); % standard deviation of velocity
figure
hold on
hb = bar(1:3,mean_velocity');
% For each set of bars, find the centers of the bars, and write error bars
pause(0.1); %pause allows the figure to be created
for ib = 1:numel(hb)
%XData property is the tick labels/group centers; XOffset is the offset
%of each distinct group
xData = hb(ib).XData+hb(ib).XOffset;
errorbar(xData,mean_velocity(ib,:),std_velocity(ib,:),'k.')
end
I'm not quite sure why the pause is required- it seems that the new graphics engine requires a little bit of time before it will recognize the figure handle properly. I've tried it in other scripts where there is more code in between the plotting and the additional math and it seems to work fine, as well as trying it just via command line, and found the same issue. This should work in any version r2014b+.

#### 5 件のコメント

Tao Liu 2017 年 2 月 22 日
Thanks very much, useful for me
Ajay Goyal 2017 年 8 月 5 日
What canbe done in case of MATLABR2013b
Tasnuba Siddiqui 2017 年 9 月 19 日
Thank you very much. It's really useful and helped me a lot!

サインイン to comment.

### その他の回答 (2 件)

Hossein 2017 年 11 月 16 日

Hi, Thank you for your answer, but unfortunately, there is no 'XOffset' property for the handle in Matlab 2017, does anyone have other ideas?

#### 2 件のコメント

the cyclist 2017 年 11 月 16 日
The code in Allison's answer works for me in version R2017b.
Are you sure you don't have some other problem?
Hossein 2018 年 9 月 21 日
Mine was 2017a, now I tested on 2017b and it worked. :) Thank you for your reply.

サインイン to comment.

Maxandre Jacqueline 2018 年 8 月 27 日
How to do this for a categorical x axis?

#### 0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。

Translated by