2

I've got a problem to find the exact location of a MATLAB bar-plot with multiple bars. Using the following code

A =[2.1974e-01   4.1398e-01   1.0889e-01   3.3550e-01;
   4.2575e-01   5.2680e-01   2.3446e-01   9.7119e-02;
   2.5702e+00   2.5594e+00   3.2481e+00   9.9964e-01];
b=bar(A);

I get the following plot

bar plot with multiple bars

Now I want to add stuff to that plot, e.g. error bars, text etc. For that reason I want to know the exact position of the individual bars.

I'm able to access individual properties using b(1). scheme, but I don't know which property belongs to the bar position. How do I get the exact location of each individual bar?

Cecilia
  • 4,512
  • 3
  • 32
  • 75
madn
  • 23
  • 2

2 Answers2

2

You are on the right track with the properties of

b = bar(A);

The specific properties you need are

  1. b.XOffset The spacing between groups of bars
  2. b.XData The index of each group of bars
  3. b.YData The height of each bar

For the y-coordinates of the top of each bar, you can simply concatenate the `b.YData values.

yb = cat(1, b.YData);

For the x-coordinates, you need to add the offset to the indices

xb = bsxfun(@plus, b(1).XData, [b.XOffset]');

Now, you have the location of the top of each bar. Here's an error bar example.

figure;
bar(A)
hold on;
for ii = 1:length(xb(:))
    plot([xb(ii), xb(ii)], [yb(ii)-0.1 yb(ii)+0.1], 'xk-')
end

Error bars on bar plot

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Cecilia
  • 4,512
  • 3
  • 32
  • 75
-1

You can use the figure property viewer to identifiy the properties of the bar postitions. Give it a try and change some values. Then you can access the properties and use the set function.

The values are the x- and y- values of the bars

M4rk0444
  • 73
  • 9
  • Please elaborate this answer, as it's rather vague at this point. Please add a screenshot showing which buttons to click and where the numbers are shown. Better still: add a way to do this programmatically, so as not to have to hand-copy the numbers each time. – Adriaan Aug 30 '17 at 09:23
  • good idea, although I couldn't find the right variable again. The only relevant information about the x-axis seems to be `X Data Source = auto` which does not help – madn Aug 30 '17 at 11:02
  • More than @Adriaan commented, this answer is wrong because using the figure properties will give the same x value to each of the bars in a specific group. – Adiel Oct 02 '17 at 12:21