Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab `bar`: Control spacing between bar groups

The following creates pairs of bars:

x = rand(10,2);
hBar = bar(x)

There is a lot of space between each pair. How can I decrease the spacing between the pairs (not between the bars within each pair)?

get(h(1)) does not reveal any likely properties to alter. Property BarWidth only controls the spacing between bars within each pair.

The Properties editor also does not reveal likely candidates.

I am using Matlab 2015b.

Afternote: Specifying a wide width argument to bar widens each bar without changing their positions relative to each other, so that will certainly shrink the gap between groups of bars. However, it also causes the bars within each group to overlap.

like image 666
user36800 Avatar asked Mar 20 '26 17:03

user36800


1 Answers

In MATLAB R2017a, bar(...,'hist') uses an older style bar graph, not using the Bar graphics objects, but using the more low-level Patch graphics objects. (I'm specifying the version number, because this is not something mentioned in the documentation, so it's possible that a newer release does this differently.)

I was able to modify the vertex locations for these Patch objects to shift the bars, increasing the space within the groups and decreasing the space between groups. By default, the bars within groups were touching using the 'hist' option.

x = rand(10,2);
hBar = bar(x,'hist');

v = hBar(1).Vertices;
v(:,1) = v(:,1) - 0.1; % shift x locations left
hBar(1).Vertices = v;

v = hBar(2).Vertices;
v(:,1) = v(:,1) + 0.1; % shift x locations right
hBar(2).Vertices = v;

It should be relatively easy to modify the code above for more fine-tuned bar placement. Note that each bar uses 5 vertices. In the case of 2 bars, the left one has round values on the right and the right one has round values on the left. You can identify these values through mod(v(:,1),1)==1. But for more bars this will not hold. Maybe separately adjusting values v(ii:5:end,1), for ii from 1 to 5, would be the simplest approach.

like image 173
Cris Luengo Avatar answered Mar 24 '26 10:03

Cris Luengo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!