How to determine the locations of bars in a bar plot?

923 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

3
On

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